5

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.

cahoskins
  • 125
  • 2
  • 9

3 Answers3

5

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

Matt Smith
  • 17,026
  • 7
  • 53
  • 103
  • 1
    I found some documentation from [Joseph Albahari](http://www.albahari.com/threading/part5.aspx#_Working_with_AggregateException) that explains this well. I think the MS documentation is confusing and it doesn't have an example. – cahoskins Aug 26 '13 at 19:25
2

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

BendEg
  • 20,098
  • 17
  • 57
  • 131
2

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

jbe
  • 6,976
  • 1
  • 43
  • 34