Skip to content

Instantly share code, notes, and snippets.

@trullock
Last active December 15, 2015 18:09
Show Gist options
  • Save trullock/5301694 to your computer and use it in GitHub Desktop.
Save trullock/5301694 to your computer and use it in GitHub Desktop.
this.cancellationTokenSource = new CancellationTokenSource();
var po = new ParallelOptions
{
MaxDegreeOfParallelism = 8,
CancellationToken = this.cancellationTokenSource.Token
};
try
{
Parallel.ForEach(list, po, (item, loopState) =>
{
if (loopState.ShouldExitCurrentIteration || loopState.IsExceptional)
loopState.Stop();
po.CancellationToken.ThrowIfCancellationRequested();
// do stuff here
});
}
catch (OperationCanceledException)
{
// we're aborting, tidy up
}
catch (Exception e)
{
// report error here
}
@trullock
Copy link
Author

trullock commented Apr 3, 2013

note: "Do stuff" is wrapped in a try catch, so it will never throw. Can AggregateExceptions be thrown by another means?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment