簡體   English   中英

如何在Android Http postasync中處理TaskCancelledException? 我不斷收到未處理的異常和應用程序崩潰

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

這是我的方法,我從oncreate方法調用它: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();
     } 
}

我在這里得到了一個任務取消的異常,但不確定如何處理,這是因為我有超時需要,以便用戶等待並盡快嘗試

這就是我如何使其工作...

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

        }
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM