【问题标题】:How to handle TaskCancelledException in Android Http postasync ? I keep getting unhandled exception and app crash如何在 Android Http postasync 中处理 TaskCancelledException?我不断收到未处理的异常和应用程序崩溃
【发布时间】:2015-09-29 09:25:14
【问题描述】:

这是我的方法,我从 oncreate 方法中调用它: 等待 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();
     } 
}

我在这里收到一个任务取消异常,但不知道如何处理它,这是因为我有一个我需要的超时,以便用户等待并尽快重试

【问题讨论】:

  • 您正在重新抛出异常,如果您不在其他地方处理它仍然未处理。
  • 我需要保持超时,这就是造成异常的原因
  • 或者我可以在异常发生之前手动取消任务吗?还是那不重要?
  • 一个TaskCanceledException 已经被抛出。为什么要用cts.ThrowIfCancellationRequested(); 重新抛出它?一旦发生超时应该怎么办?
  • 我删除了 throwifcancelrequested.. 一旦发生超时,我想显示警报并选择重试 postasync 或重新启动活动。我只是希望它此时停止崩溃

标签: c# android exception-handling android-asynctask xamarin


【解决方案1】:

这就是我让它工作的方式......

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

        }
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 2014-10-04
    • 1970-01-01
    相关资源
    最近更新 更多