【发布时间】: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