Parallel.Invoke in .Net Framework 4


Namespace: System.Threading.Tasks

Multicore-processors machines are now becoming standard. The key to performance improvements is therefore to run a program on multiple processors in parallel. 

The Task Parallel Library (TPL) is designed to make it much easier for the developer to write code that can automatically use multiple processors. Using the library, you can conveniently express potential parallelism in existing sequential code, where the exposed parallel tasks will be run concurrently on all available processors. Usually this results in significant speedups.

TPL is a major component of the Parallel FX library, the next generation of concurrency support for the Microsoft .NET Framework.

The Parallel Class :  which include
  1. Parallel.For (refer my article : http://www.c-sharpcorner.com/UploadFile/61b832/4178/
  2. Parallel.Foreach (refer my article : http://www.c-sharpcorner.com/UploadFile/61b832/4178/
  3. Parallel.Invoke
Parallel.For() and Parallel.ForEach() are useful if you have collections you need to act on or a known number of times you have to execute the same code, but what about when you have several different things (methods) you need to do? For that, we have Parallel.Invoke().

Parallel.Invoke() simply executes a list of methods passed to it, in parallel:

Example: 

static void Main(string[] args)
{
    //This line will run the methods A,B,C,D and E in parallel
    Parallel.Invoke( ()=>A, ()=>B, ()=>C, ()=>D, ()=>E);
    Console.ReadLine();
}
public static void A()
{
          //DoSomeWork of A
}
public static void B()
{
          //DoSomeWork of B
}
public static void C()
{
          //DoSomeWork of C
}
public static void D() 
{
          //DoSomeWork of D
}
public static void E()
{
          //DoSomeWork of E
}

Methods A(), B(), C(), D() and E() will be assigned to worker threads as they become available and execute in parallel. 

Happy Learning...

Up Next
    Ebook Download
    View all
    Learn
    View all