C# Threading Shorthand

January 22, 2010 by Dave
 

As the complexity of an application increases, often so does the threading complication.  I have two snippets which often come in useful when dealing with threads in C#.

Quickly execute code in the background:

new Thread((ThreadStart)delegate()
    {
        // code here is executed on a new thread
        // blocking operations will not block the calling thread
    }).Start();

Note that if this code is to be called often, a ThreadPool may be the better choice. ThreadPools’ have less overhead for instances when many threads would be created and destroyed.

Execute code that manipulates UI:

if (Control.IsHandleCreated)
{
   Control.Invoke((MethodInvoker)delegate()
   {
        // code here is safe to interact with Control
   });
}

Replace ‘Control’ with ‘this’ inside the Form class. Control may refer to any control created on the UI thread.

Comments