Simple usage and Exception Handling of parallel programming, and Exception Handling of parallel usage
When a large amount of data needs to be processed or a large number of tasks need to be completed, and each data or task is independent of each other, parallel programming can be considered. Modern computers are multi-core, and parallel programming can improve CPU utilization to increase throughput.
The Parallel. Invoke parameter can receive an array of actions.
static void Main(string[] args)
{
Test();
Console.ReadKey();
}
static void M1()
{
Console. WriteLine ("method 1 ");
}
static void M2()
{
Console. WriteLine ("method 2 ");
}
static void M3()
{
Console. WriteLine ("method 3 ");
}
static void Test()
{
Parallel.Invoke(M1,M2,M3);
}
Note that Parallel. Invoke is a synchronization method, and the result is returned only after all the delegate execution is complete.
Parallel. Invoke also receives a parameter of the ParallelOptions type to control the entire Parallel process.
The MaxDegreeOfParallelism attribute is used to set the maximum number of threads used.
The TaskScheduler attribute is used to set which thread to execute.
CancellationToken attribute. Once a delegate is set to cancel the entire parallel process.
The following is an example of using the CancellationToken attribute.
static void Main(string[] args)
{
Test();
Console.ReadKey();
}
static void M1()
{
token.Cancel();
}
static void M2()
{
Console. WriteLine ("method 2 ");
}
static void M3()
{
Console. WriteLine ("method 3 ");
}
static CancellationTokenSource token = new CancellationTokenSource();
static void Test()
{
ParallelOptions op = new ParallelOptions();
op.CancellationToken = token.Token;
try
{
Parallel.Invoke(op,M1, M2, M3);
}
catch (OperationCanceledException ex)
{
Console.WriteLine(ex);
}
}
In the preceding example, the CancellationTokenSource instance method Cancel is called to Cancel the execution of a delegate. Once the Parallel. Invoke method receives a real parameter of the ParallelOptions type, the entire Parallel action can be canceled.
Parallel. Invoke is applicable when a large number of tasks are encountered and each task is independent of each other.
In general, Parallel. ForEach is suitable for processing a large amount of data, and each piece of data is independent of each other.
static void Main(string[] args)
{
IEnumerable<int> lst = new List<int> {1, 2, 3,4,5,6};
Parallel.ForEach(lst, i => DisplayDigit(i));
Console.ReadKey();
}
static void DisplayDigit(int i)
{
Console.WriteLine(i);
}
Parallel. For is used when the data processing process is indexed.
In. NET, all parallel exceptions are packaged in AggregationException. The exception is roughly handled as follows:
try
{
Parallel.Invoke(
() => throw new Exception();
() => throw new Exception();
);
}
catch(AggregateException ex)
{
ex.Handle(
exception => Console.WriteLine(ex);
return true;
);
}