-1

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

这是我想要在布尔值变为 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);

如何验证令牌是否在没有 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;
    }
}

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

4

1 回答 1

5

I'm assuming token is a CancellationToken?

You wouldn't need a loop, instead take a look at CancellationToken.ThrowIfCancellationRequested. By calling this, the CancellationToken class will check if it has been canceled, and kill the task by throwing an exception.

Your task code would then turn into something like:

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);

If the cancellation exception is thrown, the task returned from Task.Factory.StartNew will have its IsCanceled property set. If you're using async/await, you'll need to catch the OperationCanceledException and clean things up appropriately.

Check out the Task Cancellation page on MSDN for more info.

于 2014-06-19T17:08:35.027 回答