[英]Cancellation Task
I need to cancel task that using a long-running method from dll (MethodFromDll() in this example) Where I can call cancellationToken.ThrowIfCancellationRequested() method to cancel this Task? 我需要取消从dll使用长时间运行的方法的任务(在此示例中为MethodFromDll()),在哪里可以调用cancelToken.ThrowIfCancellationRequested()方法来取消此Task?
tokenSource = new CancellationTokenSource();
CancellationToken cancellationToken = tokenSource.Token;
t = Task.Factory.StartNew(() => {
try {
...some code
// I need to cancel this task manually if method not answer
// or there is no wish to wait
MethodFromDll();
...some code
} catch {
...some code
}
}, cancellationToken);
Call Cancel on your CancelationTokenSource and register callback 在CancellationTokenSource上调用Cancel并注册回调
tokenSource = new CancellationTokenSource();
CancellationToken cancellationToken = tokenSource.Token;
return Task.Factory.StartNew(() =>
{
try
{
cancellationToken.Register(() =>
{
//call api method to stop long running method
});
//...some code
}
catch
{
}
}, cancellationToken);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.