Question of the day: Threading

Here’s a little question about Threading – this would be a great interview question, in my opinion!

Given the code below:

public class Producer
{
    [ThreadStatic]
    readonly static private Producer _instance = new Producer();

    static private int _instanceCount;
    readonly private int _instanceId;

    private Producer()
    {
        _instanceId = ++_instanceCount;
    }

    static public Producer Instance
    {
        get { return _instance; }
    }

    public string Name
    {
        get
        {
            return String.Format("Instance {0} of {1}",
                _instanceId, _instanceCount);
        }
    }
}

public class Consumer
{
    public Consumer()
    {
        Thread t1 = new Thread(IdentifyProducer);
        t1.Start();

        Thread t2 = new Thread(IdentifyProducer);
        t2.Start();

        t1.Join();
        t2.Join();
    }

    public void IdentifyProducer()
    {
        Console.WriteLine(Producer.Instance.Name);
    }
}

What will happen when you create a new instance of the Consumer class?

Posted in Daily Question, Threading at June 30th, 2010. 2 Comments.

Star Sizing and Grid Size Sharing in WPF

They don’t work together. Full stop. Thank you Microsoft. The only way around this is to manually bind your columns/rows of one grid to another instead of using star sizing. Thanks to this article we can use this:

<Grid.ColumnDefinitions>
<ColumnDefinition Width="{Binding ElementName=OtherGrid}, Path=ColumnDefinitions[0].Width}" />
</Grid.ColumnDefinitions>
Posted in .Net at June 22nd, 2010. No Comments.

DateTime Localization in ASP .NET

You’ve got an ASP .NET app and you need to display a date. Normally that just involves the old DateTime.ToShortDateString() or DateTime.ToString(“d”) and you continue coding on your merry little way. But what happens when your users are from different countries and expect different date formats.  Between Australia, USA and Japan there are 3 different date formats.

Then answer? The HttpRequest’s UserLanguages. This string array basically maps to the following languages that you can setup in your browser:

Now for the code:


CultureInfo culture = Request.UserLanguages != null
? CultureInfo.CreateSpecificCulture(Request.UserLanguages[0])
: CultureInfo.CurrentCulture;
myLabel.Text = DateTimeOffset.Now.ToLocalTime().ToString("d", culture);
Don’t forget to check if the UserLanguages is not null since you can remove all the values from the list if you like.
Also, if you are looking at ways to do this client side, ScottGu’s Blog has a nice post on a new jquery plugin for this.

* Update *
Just realised that you don’t need to any of this if you use the following in your web.config:

<globalization uiCulture="auto" culture="auto" />
Posted in .Net, Asp.Net, C# at June 18th, 2010. No Comments.

Quickduck logo