Ivan-Mark Debono
Ivan-Mark Debono

Reputation: 16290

Rethrow exception with async task?

I have this code:

try
{
    await Task.Run(() =>
    {
        token.ThrowIfCancellationRequested();
        //Call WebApi...
    }, token);
}
catch (OperationCanceledException oex)
{ }
catch
{
    throw;
}

The method within await either returns code 200 or throws a particular exception that I want to evaluate.

As the action is cancelable, an OperationCanceledException might be thrown and I just want to ignore it.

The above should work. However is it possible to consolidate both catch statements with the new C# 6.0 syntax by using when?

Upvotes: 1

Views: 1060

Answers (1)

Scott Chamberlain
Scott Chamberlain

Reputation: 127543

You don't need C# 6, just get rid of the last catch block and have only the OperationCanceledException

try
{
    await Task.Run(() =>
    {
        token.ThrowIfCancellationRequested();
        //Call WebApi...
    }, token);
}
catch (OperationCanceledException oex)
{ }

The one thing you might want to do with C# 6 is check that the token that was used to raise the excption is the token you passed in

try
{
    await Task.Run(() =>
    {
        token.ThrowIfCancellationRequested();
        //Call WebApi...
    }, token);
}
catch (OperationCanceledException oex) when (oex.CancellationToken == token)
{ }

Or using the old style

try
{
    await Task.Run(() =>
    {
        token.ThrowIfCancellationRequested();
        //Call WebApi...
    }, token);
}
catch (OperationCanceledException oex)
{ 
    if(oex.CancellationToken != token)
        throw;
}

Upvotes: 1

Related Questions