如何取消正在等待超时的任务而不抛出异常
使用取消标记取消超时(超时结束之前)的任务时,会引发异常。示例:
mytask.start();
bool didTaskRunInTime = mytask.wait(5 mins, _cancelToken);
这意味着我不能像下面这样继续下去。
//was the task cancelled
if (_cancelToken.IsCancelRequested)
{
// log cancel from user to file etc
}
if (didTaskRunInTime )
{
int taskResult = myTask.Result;
// log result to file
}
else if (!_cancelToken.IsCancelRequested)
{
// Tell user task timed out , log a message etc
}
我必须在 catch 块中完成所有这些操作,并且我的代码看起来很混乱。这样做的正确方法是什么?
When canceling a task that has a timeout (before the timeout has ended) using a cancel token an exception is thrown. Example:
mytask.start();
bool didTaskRunInTime = mytask.wait(5 mins, _cancelToken);
Which means I cannot go on like below.
//was the task cancelled
if (_cancelToken.IsCancelRequested)
{
// log cancel from user to file etc
}
if (didTaskRunInTime )
{
int taskResult = myTask.Result;
// log result to file
}
else if (!_cancelToken.IsCancelRequested)
{
// Tell user task timed out , log a message etc
}
I will have to do all this in my catch block and my code is looking messy. What is the correct way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
Task.WaitAny
调用只是该任务的数组。然后,您可以根据任务的状态采取行动,但方法会返回。示例代码:请注意,如果任务出错,您应该“观察”异常,以避免它在最终确定时发生爆炸:)
You could call
Task.WaitAny
with an array of just that task. Then you can act on the status of the task, however the method returns. Sample code:Note that if the task is faulted, you should "observe" the exception in order to avoid it going bang when it's finalized :)
尝试使用OperationCanceledException
try to use OperationCanceledException