如何在没有 LOOP 的情况下取消任务

C1r*_*dec -1 c# async-await cancellation-token

嗨,我一直在论坛上阅读了很多,但我无法找到问题的答案...

这是我想在布尔值变为 TRUE 时取消的函数:

Task<PortalODataContext> task = Task.Factory.StartNew(() =>
        {
            var context = connection.ConnectToPortal();
            connection.ListTemplateLib = this.ShellModel.ConnectionManager.GetTemplateLibrarys(connection);
            connection.ListTemplateGrp = this.ShellModel.ConnectionManager.GetTemplateGroups(connection, connection.TemplateLibraryId);
            connection.ListTemplates = this.ShellModel.ConnectionManager.GetTemplates(connection, connection.TemplateGroupId);
            return context;
       }, token);
Run Code Online (Sandbox Code Playgroud)

如何在没有 LOOP 的情况下验证令牌是否收到取消请求?

类似的东西:

if (token.IsCancellationRequested)
{
    Console.WriteLine("Cancelled before long running task started");
    return;
}

for (int i = 0; i <= 100; i++)
{
    //My operation

    if (token.IsCancellationRequested)
    {
        Console.WriteLine("Cancelled");
        break;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是我没有需要循环的操作,所以我不知道该怎么做......

Com*_*Cow 5

我假设token是一个CancellationToken?

您不需要循环,而是查看CancellationToken.ThrowIfCancellationRequested。通过调用这个,CancellationToken该类将检查它是否已被取消,并通过抛出异常终止任务。

然后你的任务代码会变成这样的:

using System.Threading.Tasks;
Task.Factory.StartNew(()=> 
{
    // Do some unit of Work
    // .......

    // now check if the task has been cancelled.
    token.ThrowIfCancellationRequested();

    // Do some more work
    // .......

    // now check if the task has been cancelled.
    token.ThrowIfCancellationRequested();
}, token);
Run Code Online (Sandbox Code Playgroud)

如果抛出取消异常,则返回的任务Task.Factory.StartNew将设置其IsCanceled属性。如果您使用 async/await,则需要捕获OperationCanceledException适当并清理内容。

查看MSDN 上的任务取消页面了解更多信息。