How to handle TaskCancelledException in Android Http postasync ? I keep getting unhandled exception and app crash

半世苍凉 提交于 2019-12-11 23:09:08

问题


Here is my method, i call it from the oncreate method: await httpPost(newscan);

public async Task HttpPost(Scan s)
{
    var client = new HttpClient();

    // This timeout is whats causing the taskCancelledException....
    client.Timeout = TimeSpan.FromSeconds(8);
    var cts = new CancellationToken();

    try
    {
        var json = JsonConvert.SerializeObject(s);
        await client.PostAsync("http://10.0.0.103:4321/scan", new StringContent(json), cts);
        newScan.Success = "Success";
        codes.Add(newScan.ScanValue + "     " + DateTime.Now.ToShortTimeString() + "    " + newScan.Success);
     }
     catch (TaskCanceledException ex)
     {
        if (ex.CancellationToken == cts)
        {
            // Here is where the unhandled exception crashes


            client.Dispose();
        }
        else
        {
            client.CancelPendingRequests();
        }
     }
     catch (AggregateException ae)
     {
        newScan.Success = "Send Error";
        codes.Add(newScan.ScanValue + "     " + DateTime.Now.ToShortTimeString());
        client.Dispose();

     }
     catch (Exception ex)
     {
        client.Dispose();
     } 
}

Im getting a task cancelled exception here but not sure how to handle it, It happens because I have a Time out which I need so that user dosent wait and gets try again asap


回答1:


This is how I got it to work...

public async Task<string> CallService()
{
    client.DefaultRequestHeaders.Add("ContentType", "application/json");
    client.Timeout = TimeSpan.FromSeconds(5);
    var cts = new CancellationTokenSource();
    try
    {
        Toast.MakeText(this, "Sending Barcode " + newScan.ScanValue, ToastLength.Long).Show();
        await HttpPost(cts.Token);

        return "Success";
    }
    catch (Android.Accounts.OperationCanceledException)
    {
        return "timeout and cancelled";
    }
    catch (Exception)
    {
        return "error";
    }
}

private async Task HttpPost(CancellationToken ct)
{
    var json = JsonConvert.SerializeObject(newScan);

    try
    {
        var response = await client.PostAsync("http://10.0.0.103:4321/Scan", new StringContent(json), ct);
        response.EnsureSuccessStatusCode();
        newScan.Success = "Success";
        codes.Add(DateTime.Now.ToShortTimeString() + "   " + newScan.ScanValue + " " + 
            "\n" + newScan.Success);

    }
    catch (Exception ex)
    {
        Log.Debug(GetType().FullName, "Exception: " + ex.Message);
        ErrorMessage = ex.Message;
    }
    finally
    {
        if (newScan.Success != "Success")
        {

            builder.Show();
            codes.Add(DateTime.Now.ToShortTimeString() + "   " + newScan.ScanValue + " \n" + ErrorMessage);

        }
    }

}


来源:https://stackoverflow.com/questions/32840402/how-to-handle-taskcancelledexception-in-android-http-postasync-i-keep-getting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!