jmichas
jmichas

Reputation: 1159

How to handle TaskCanceledException?

I have a xamarin app that uses plugins for media access to select or take a photo.

In my relay command I have this:

try
{
    var mediaFile =
        await
            _mediaPicker.SelectPhotoAsync(new CameraMediaStorageOptions());

    using (var memoryStream = new MemoryStream())
    {
        mediaFile.Source.CopyTo(memoryStream);
        ...do image stuff here
    }
}
catch (TaskCanceledException taskCanceled)
{
    Debug.WriteLine(taskCanceled.Message);
}

Is there a better way to handle task cancellation exceptions in general? The SelectPhotoAsync doesn't take a cancellation token. Is an empty catch ok here? It is perfectly fine for a user to cancel the operation.

Thanks.

Upvotes: 5

Views: 3650

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 457057

Generally, you should catch OperationCanceledException rather than TaskCanceledException. Other than that, your approach looks fine; the proper way to handle the exception is to catch it.

Upvotes: 9

Related Questions