0

With below code Im trying to update customer model on cache & sql db asynchronously. Either one of the tasks or both tasks may fail & it will leads to AggregateException.

In the AggregateException I want to know which exception related to which task. Lets say inside AggregateException, I have Exception1 & Exception2. Want to know Exception1 originated by "updateCacheCustomerTask" failure while Exception2 originated by "updateDBCustomerTask" failure. How to do that? please suggest.

   public async Task UpdateCustomerAsync(T model)
    {
        var updateCacheCustomerTask = Task.Run(() =>
        {
            throw new Exception();
        });

        var updateDBCustomerTask = Task.Run(() =>
        {
            throw new Exception();
        });

        await Task.WhenAll(updateCacheCustomerTask , updateDBCustomerTask ).ContinueWith(result =>
        {
            if (result.Exception != null)
            {
                throw result.Exception;
            }
        });

    }

1 Answers1

0

You can do throw new Task1Exception(msg, ex); in one, and throw new Task2Exception(msg, ex) in the other. You'll need to define as many Task...Exception classes as you have Tasks, with the needed constructor.

Passing in ex means that InnerException is set to the actual Exception that occurred, captured if needed using a try-catch.

You can also do throw new Exception(msg, ex); in all Tasks, so without using custom Exception classes, but then you'll need to make sure that you can distinguish the instances using the contents of the msg values.

Peter B
  • 22,460
  • 5
  • 32
  • 69