Thursday, January 30, 2014

Threading in C#: 7 Things you should always remember about

Have you ever spent a few hours on trying to debug a non-deterministic problem occurring in your multi-threading application? If so, then you should definitely read this article. If not it is anyway a good way of revising your current knowledge about threading challenges in C#.  Being aware of some common facts about threading can help you considerably in building well-designed, error-proof multi-threading applications in the future. 

1. Threads share data if they have a common reference to the same object instance

The code below:

class SomeClass
{
    private bool _isWorkDone;
    static void Main(string[] args)
    {
        SomeClass someClass = new SomeClass();
        Thread newThread = new Thread(someClass.DoWork);
        newThread.Start();
        someClass.DoWork();
        Console.Read();
    }
    void DoWork()
    {
        if (!_isWorkDone)
        {
            _isWorkDone = true;
            Console.WriteLine("Work done");
        }
    }
}

When executed, results in:

Work done

printed on the screen.

As you can see in the  example above, both threads (the main one and newThread) call DoWork() method on the same instance of SomeClass. As a result, although the _isWorkDone field is non-static, they share it. In consequence "Work done" is printed on the screen just once, whereas a programmer who is not aware of the above would expect it be printed twice.

2. "Finally" blocks in background threads are not executed when the process terminates

Read more: Goyello blog