Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 874
jmichas Avatar asked Jan 14 '16 06:01

jmichas


1 Answers

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.

like image 131
Stephen Cleary Avatar answered Oct 14 '22 10:10

Stephen Cleary