tausiq
tausiq

Reputation: 957

Xamarin.Forms System.Threading.Tasks.TaskCanceledException

We have a Xamarin.Forms application in production. In our testing phase we didn't encounter such issues. However, in Azure Mobile Center we are getting a number of crash issues. For example, one crash issue looks like below,

A task was canceled.

1 TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task)
2 TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task)
3 TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task)
4 TaskAwaiter`1[TResult].GetResult ()
5 HttpClientHandler+<SendAsync>d__63.MoveNext ()
6 ExceptionDispatchInfo.Throw ()
...
17 RequestBuilderImplementation+<buildCancellableTaskFuncForMethod>c__AnonStoreyA`1+<buildCancellableTaskFuncForMethod>c__async9[T].MoveNext ()
18 ExceptionDispatchInfo.Throw ()
23 APIClient+<Portfolio>d__6.MoveNext ()
24 ExceptionDispatchInfo.Throw ()
29 PortfolioPage+<LoadPortfolio>d__3.MoveNext ()
30 ExceptionDispatchInfo.Throw ()

In title section it's showing, System.Threading.Tasks.TaskCanceledException

I have a page named PortfolioPage and a method named LoadPortfolio. Here is the method,

async void LoadPortfolio()
{
    try
    {
        APIResponse.Portfolio portfolio = await new APIClient().Portfolio(selectedDate);
        MessagingCenter.Send<PortfolioPage, APIResponse.Portfolio>(this, "LoadedPortfolio", portfolio);
    }
    catch (ApiException e)
    {
        Debug.WriteLine(e.Message);
        if (e.StatusCode == System.Net.HttpStatusCode.Unauthorized) UIUtil.gotoAuthenticate(this);
        else
            MessagingCenter.Send<PortfolioPage, APIResponse.Portfolio>(this, "LoadedPortfolio", null);
    }
}

I am new to Xamarin and C#. Not sure how to extract information from this error log and how to resolve the TaskCanceledException issue. Any help is appreciated.

Thanks in advance.

Upvotes: 2

Views: 1648

Answers (1)

JoeTomks
JoeTomks

Reputation: 3276

The 'HttpClientHandler' functions in a similar way to Tasks from the System.Threading.Tasks; library. What this means is that it throws an exception when it recieves either a cancellation request, or the response is unsuccessful for some 'expected' reason.

I'd suggest wrapping the request in a try/catch block and figure out how you'd like to handle 'ThrowForNonSuccess' exceptions.

Upvotes: 3

Related Questions