C# Threading Shorthand
January 22nd, 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) { try { Control.Invoke((MethodInvoker)delegate() { // code here is safe to interact with Control }); } catch(Exception) { // even though IsHandleCreated, Invoke may throw exceptions, they should be // caught and dealt with outside the handling of actual errors } }
Replace ‘Control’ with ‘this’ inside the Form class. Control may refer to any control created on the UI thread.
Posted in Code Snippets