Skip to content

Instantly share code, notes, and snippets.

@jimmymain
Created November 19, 2015 09:05
Show Gist options
  • Save jimmymain/2bcc3ba6cd3fadff1673 to your computer and use it in GitHub Desktop.
Save jimmymain/2bcc3ba6cd3fadff1673 to your computer and use it in GitHub Desktop.
wait fault
public static void WaitUnlessFault( Task[] tasks, CancellationToken token )
{
var cts = CancellationTokenSource.CreateLinkedTokenSource(token);
foreach ( var task in tasks ) {
task.ContinueWith(t =>
{
if ( t.IsFaulted ) cts.Cancel();
},
cts.Token,
TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Current);
}
try {
Task.WaitAll(tasks, cts.Token);
}
catch ( OperationCanceledException ex ) {
var faultedTaskEx = tasks.Where(t => t.IsFaulted)
.Select(t => t.Exception)
.FirstOrDefault();
if ( faultedTaskEx != null )
throw faultedTaskEx;
else
throw;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment