[英]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.