Confusion over AggregateException Handle method

6k views Asked by At

ReSharper was giving me a CoVariantConversion warning so I decided to google this and see how to fix it. I came accross this snippet of code:

 // ReSharper disable CoVariantArrayConversion
 try
 {
    Task.WaitAll(taskList.ToArray());
 }
 catch (AggregateException ex)
 {
    ex.Handle(e => true);
 }
 // ReSharper restore CoVariantArrayConversion

This part is confusing me:

 ex.Handle(e => true);

What does it do? I would think that it does nothing.

3

There are 3 answers

0
BendEg On

This say, that the Exception is handled, nothing else.

1
Matt Smith On

You are correct: the line can be removed and have the same effect (causing all the exceptions to be considered "handled") as if the line was there.

The only time it would be useful is if the lambda could return false for some exceptions (which it doesn't in this case).

0
jbe On

Here is a sample that Shows how the Handle method could be used:

Task task = Task.Factory.StartNew(() => 
{ 
    throw new UnauthorizedAccessException(); 
}); 
try
{
    task.Wait();
}
catch (AggregateException ex)
{
    ex.Handle(x =>
    {
        if (x is UnauthorizedAccessException)
        {
            // Handle this exception...
            return true;
        }
        // Other exceptions will not be handled here.
        return false;
    });
}

The sample comes from this article: Asynchronous Programming - Exception Handling