如何使用取消令牌取消C#中的阻止任务? [英] How do I cancel a Blocked Task in C# using a Cancellation Token?
问题描述
我有一个总是被阻止的任务,并且有一个CancellationToken传递给它,用于取消任务。但是,Continuation任务永远不会执行,而是设置为在Task取消后执行。代码是:
I have a Task which is always blocked and I have a CancellationToken passed into it which is used to cancel the task. However the Continuation task is never executed which is set to execute on Task's cancellation. The code is:
_tokenSrc = new CancellationTokenSource();
var cnlToken = _tokenSrc.Token;
Task.Run(() =>
// _stream.StartStream() blocks forever
_stream.StartStream(), cnlToken)
.ContinueWith(ant =>
{
_logger.Warn("Stream task cancellation requested, stopping the stream");
_stream.StopStream();
_stream = null;
_logger.Warn("Stream stopped and task cancelled");
}, TaskContinuationOptions.OnlyOnCanceled);
稍后在代码中的其他地方...
Later somewhere else in the code ...
_tokenSrc.Cancel();
我不得不对_stream.StartStream()使用Task的原因是,此调用将永远阻塞(一个我无法控制的api,请注意_stream指的是从网络服务流式传输数据的第三方Api),所以我不得不在另一个线程上调用它。
The reason I had to use a Task for _stream.StartStream() is that this call blocks forever (an api on which I have no control, note that _stream refers to a thirdparty Api which streams data from a webservice) so I had to invoke it on another thread.
什么取消任务的最佳方法是什么?
What is the best way to cancel the task?
推荐答案
[更新]
我将代码更改为以下代码以解决问题:
I changed the code to below which fixed the problem:
Task.Run(() =>
{
var innerTask = Task.Run(() => _stream.StartStream(), cToken);
innerTask.Wait(cToken);
}, cToken)
.ContinueWith(ant =>
{
_logger.Warn("Stream task cancellation requested, stopping the stream");
_stream.StopStream();
_stream = null;
_logger.Warn("Stream stopped and task cancelled");
}, TaskContinuationOptions.OnlyOnCanceled);
这篇关于如何使用取消令牌取消C#中的阻止任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!