To exit Parallel.Invokeas early as possible, you need to do three things:
- Schedule an action that determines whether you want to exit earlier than the first action. Then it was planned earlier (perhaps as the first, but not guaranteed), so you will soon find out if you want to exit.
- ,
AggregateException, . - . ,
IsCancellationRequested.
:
var cts = new CancellationTokenSource();
try
{
Parallel.Invoke(
new ParallelOptions { CancellationToken = cts.Token },
() =>
{
if (!person.IsVegetarian)
{
cts.Cancel();
throw new PersonIsNotVegetarianException();
}
},
() => { GetAgeFromWebServiceX(person, cts.Token) },
() => { GetNameFromWebServiceY(person, cts.Token) },
() => { GetIDFromWebServiceZ(person, cts.Token) }
);
}
catch (AggregateException e)
{
var cause = e.InnerExceptions[0];
// Check if cause is a PersonIsNotVegetarianException.
}
, , , . , GetAgeFromWebServiceX , .