C# Updated on Threading with .net 4

With .NET 4 we now have better ways of handling threads. So in this post I'm going to demonstrate several ways of creating and waiting for threads to finish.

First example is creating 10 threads with the new Task.Factory.StartNew() method then we call Task.WaitAll and the framework handles the rest. This call will however block until all the tasks are finished.

 // Wait for all tasks to complete.  
       Task[] tasks = new Task[10];  
       for (int i = 0; i < 10; i++)  
       {  
         tasks[i] = Task.Factory.StartNew(() => DoSomeWork(10000000));  
       }  
       Task.WaitAll(tasks);  

The second way allows us to no block.

 var task1 = DoWorkAsync();  
 var task2 = DoMoreWorkAsync();  
 await Task.WhenAll(task1, task2);  

Comments

Popular posts from this blog

String.Replace vs Regex.Replace

C# Form Application in Kiosk Mode/Fullscreen

C# using a transaction with ODBC