Parallel.Invoke - Exception Handling

My code runs 4 functions to populate the information (using Invoke) for the class, for example:

class Person
{
    int Age;
    string name;
    long ID;
    bool isVegeterian

    public static Person GetPerson(int LocalID)
    {
        Person person;
        Parallel.Invoke(() => {GetAgeFromWebServiceX(person)}, 
                        () => {GetNameFromWebServiceY(person)},
                        () => {GetIDFromWebServiceZ(person)},
                        () => 
                        {
                           // connect to my database and get information if vegeterian (using LocalID)
                           ....
                           if (!person.isVegetrian)
                               return null
                           ....
                        });
     }
}

My question is: I cannot return null if it is not vetarian, but I want to stop all threads, stop processing and just return null. How can this be achieved?

+5
source share
3 answers

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 , .

+7

, , AggregateException GetPerson (.. try/catch Parallel.Invoke), , , null.

, . , , , . , boolean, , - , , ... , .

, "" Parallel.Invoke , .

+4

Do you really need to download yours Personfrom the database first? Because your code calls web services with a null value.

If your logic is really consistent, do it sequentially and do only parallel, which makes sense.

+1
source

All Articles