简体   繁体   English

如何在Android Http postasync中处理TaskCancelledException? 我不断收到未处理的异常和应用程序崩溃

[英]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); 这是我的方法,我从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();
     } 
}

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

        }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 HttpClient.PostAsync 崩溃应用。 如何捕捉异常? - HttpClient.PostAsync crash app. How to catch the Exception? 如何在未处理的异常上崩溃 - How to crash on unhandled Exception 如何在未处理的任务异常上崩溃? - How to crash on unhandled Task exception? 将WPF应用程序迁移到dotnet Core 3后获取TaskCancelledException - Getting TaskCancelledException after migrating a WPF app to dotnet Core 3 如何在Windows 8.1中使用SearchBox时优雅地处理TaskCancelledException - How to gracefully handle TaskCancelledException while using SearchBox in Windows 8.1 我试图解密C#中的自动密钥密码,但我一直得到一个未处理的异常 - I am trying to decrypt the autokey cipher in C#, but I keep getting an unhandled exception 为什么后台线程中未处理的异常不会导致应用程序域崩溃? - Why unhandled exception in a background thread doesnt crash the app domain? C#应用程序中未处理的异常会导致应用程序崩溃吗? - Unhandled exception in C# application does it crash the app? 如何处理对象处置异常是C#中未处理的异常? - How to handle object disposed exception was unhandled Exception in c#? 防止Winform在未处理的异常上崩溃 - Prevent Winform to crash on unhandled exception
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM