【发布时间】:2015-04-19 00:54:20
【问题描述】:
我目前正在使用串行端口,即使设置了自己的超时,我使用的 API 有时也会在读取时挂起。
这不是一个大问题,但是当发生这种情况并且需要关闭挂起的线程时,我需要做一些工作。我已经尝试过以下方法,但它一直给我带来问题,因为 API 调用没有终止,但允许在其余代码继续时继续,并且抛出了 TimeoutException。如何使用Tasks 在一定时间后取消挂起的任务?
CancellationToken token = new CancellationToken();
var task = Task.Factory.StartNew(() =>
{
CallingAPIThatMightHang(); // Example
}, token);
if (!task.Wait(this.TimeToTimeOut, token))
{
throw new TimeoutException("The operation timed out");
}
【问题讨论】:
-
简短回答:你不能;至少你不能可靠。相关阅读blogs.msdn.com/b/ericlippert/archive/2010/02/22/…
-
使用
Task真的有限制吗?只需创建Thread,然后根据需要使用Abort终止它 -
我希望避免这种情况,但我知道我必须这样做。
-
@n0rd As soon as you type new Thread(), it’s over; your project already has legacy code. ... :) 还有 ...
Thread.Abortis evil 即不清理 ...
标签: c# multithreading task-parallel-library