Forum Xamarin.Android

Facing this exception "System.Threading.Tasks.TaskCanceledException Message=A task was canceled."

I'm using MVVM cross in my application. I face System.Threading.Tasks.TaskCanceledException Message=A task was canceled in this part of the code.

public override void ViewDestroy(bool viewFinishing = true)
     {
                if (viewFinishing
                    && CloseCompletionSource != null
                    && !CloseCompletionSource.Task.IsCompleted
                    && !CloseCompletionSource.Task.IsFaulted)
                    {
                        CloseCompletionSource?.TrySetCanceled();
                    }
                base.ViewDestroy(viewFinishing);
        }

This exception raises only some times but not all the time.

Answers

  • ColeXColeX Member, Xamarin Team Xamurai

    TrySetCanceled method may lead TaskCanceledException .

    The proper consuming code for a task that can be canceled is to wrap the await in a try/catch and catch OperationCanceledException. For various reasons (many historical), some APIs will cause OperationCanceledException and some will cause TaskCanceledException. Since TaskCanceledException derives from OperationCanceledException, consuming code can just catch the more general exception.

    Check the detailed explanation : https://stackoverflow.com/a/43681980/8187800 .

Sign In or Register to comment.