In nowadays
we have multiple core CPU machine that enables to process the multiple thread
on same time/simultaneously. .NET framework provides class library and runtime
support to write efficient the parallel programming code. For more information
about the parallel programming architecture please visit Parallel Programming in .NET.
In this
article, we will discuss about the Parallel.Invoke method and how to write the
parallel programming code with help of this.
Parallel.Invoke
method provides a simple way in which a number of Tasks may be created and
executed in parallel and we don’t need to create a complicated threading code.
Here is syntax:
public static void Invoke(params
Action[] actions);
Parallel.Invoke
takes as array of delegates of method and it execute each of provided methods
in parallel.
public static void Invoke(System.Threading.Tasks.ParallelOptions parallelOptions, params Action[] actions);
In second
method, we have more control over execution of parallel operations. With help
of additional parameter parallelOptions, we can control the max degrees of
parallelism means the maximum number of concurrent tasks and
we can also cancel the operation by using CancellationToken property.
Here is a
simple example of Parallel.Invoke method:
static void Main()
{
List requests = GetRequests();
ParallelOptions
parallelOptions = new
ParallelOptions();
parallelOptions.MaxDegreeOfParallelism = 10;
foreach (Request request in requests)
{
Parallel.Invoke(parallelOptions, async() => await
ProcessRequest(request));
}
}
static async Task
ProcessRequest(Request request)
{
// Process Request and produce response asynchronously
}
In above
example, we are controlling execution of parallel operations and only 10 max concurrent
tasks are allowed.
No comments:
Post a Comment