有一个top任务会启动另一个任务。
var token = _cancellationTokenSource.Token;
_task = new Task(() => WorkAction(this, token), token); //Top level task内部任务实现为:
public string FindDevice(IProgressViewModel progressViewModel,
CancellationToken cancellationToken) {
for (int i = 0; i < orderedComPortsList.Count; i++) {
try {
cancellationToken.ThrowIfCancellationRequested();
} catch (OperationCanceledException) {
return null;
}
string curPort = orderedComPortsList[i];
if (InnerIsDeviceOnline(deviceModelId, curPort)) //The real long work
return curPort;
progressViewModel.CurrentValue = i;
}
return null;
}在此实现中,只有当最后一个InnerIsDeviceOnline结束时才会发生取消。如何实现FindDevice使其可以立即取消?
更新1。
我们能做这样的事情吗:
bool? result = null;
Task<bool> parent = new Task<bool>(() => {
bool? res = result;
Task.Factory.StartNew(() => {
while (res==null) {
cancellationToken.ThrowIfCancellationRequested();
Thread.Sleep(50);
}
}, TaskCreationOptions.AttachedToParent);
result = InnerIsDeviceOnline(deviceModelId, comPort);
return result.Value;
}, cancellationToken);
return parent;它的问题是它永远不会结束(我不知道为什么)。但这会让我们立即取消订单。
发布于 2014-03-24 23:05:19
为了优雅地取消长时间运行的操作,您的整个API需要在您需要的特定粒度支持取消。在长时间运行的操作的应用程序接口不支持CancellationToken的情况下,您需要提供一个接口层来提供这种支持。例如,异步WebRequest.BeginGetResponse不支持CancellationToken,但我能够通过此扩展方法支持它,该方法调用Abort()以响应CancellationToken被取消:
https://stackoverflow.com/questions/22610044
复制相似问题