- The
Parallel
class has a couple of static methods that you can achieve parallelism work.
- You should use the
Parallel
class only when your code doesn’t have to be executed sequentially.
- Increasing performance with parallel processing happens only when you have a lot of work to be done that can be executed in parallel.
- For smaller work sets or for work that has to synchronize access to resources, using the
Parallel
class can hurt performance.
Parallel.For()
var startIndex = 0;
var iterations = 10;
var series = new string[iterations];
Parallel.For(startIndex, iterations, (i) => series[i] = i.ToString());
Console.WriteLine(string.Join("", series));
Parallel.For()
returns ParallelLoopResult
object that contains information about the loop result.
- You can cancel the loop by using the
ParallelLoopState
object.
- You have two options to do this: Break or Stop.
- Break ensures that all iterations that are currently running will be finished.
- Stop just terminates everything.
- In the following example, when breaking the parallel loop, the result variable has an
IsCompleted
value of false and a LowestBreakIteration
of 500.
- When you use the
Stop
method, the LowestBreakIteration
is null.
ParallelLoopResult result = Parallel.For(0, 1000, (int i, ParallelLoopState loopState) =>
{
if (i == 500)
loopState.Break();
});
if (!result.IsCompleted)
Console.WriteLine(result.LowestBreakIteration);
Parallel.ForEach()
- The
ForEach
call does the process in parallel, executing as many threads as the API determines is efficient.
- Efficiency is determined by a “hill climbing” algorithm in which additional threads are created until the overhead of additional threads begins to decrease overall performance, at which point the most efficient number of threads is determined (dynamically).
- The degree of parallelism corresponds to the number of threads that run simultaneously at any particular time.
void EncryptFiles(string directoryPath)
{
var files = Directory.GetFiles(directoryPath);
Parallel.ForEach(files, (fileName) => File.Delete(fileName));}
}
Parallel.Invoke()
Parallel.Invoke()
takes any number of Action
delegates and invokes them asynchronously and waits for them to rejoin.
int result;
Parallel.Invoke(
SomeMethod,
() => SomeOtherMethod(5, 10),
() => { result = YetAnotherMethod(5, 10, 15); });
Parallel Exception Handling
- If an exception throws while the loop is executing, the exception type is a
System.AggregateException
.
- In this way, all exceptions within the loop are handled with a single try/catch block.