简体   繁体   中英

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

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

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);

        }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM