为什么取消取消取消?

时间:2016-10-19 18:43:02

标签: c# azure-cloud-services cancellationtokensource

在我调用我的第一个异步方法(在此示例中为GetBar())之后,似乎正确,CancellationToken的IsCancellationRequested设置为true,但我不想要并且不明白它为什么会发生。

如果重要的话,这是Azure Cloud Service工作者角色。

public class WorkerRole : RoleEntryPoint
{
    private CancellationTokenSource cancellationTokenSource;
    private Task runTask;

    public override void Run()
    {
        this.cancellationTokenSource = new CancellationTokenSource();
        this.runTask = Task.Run(() => Foo.Bar(this.cancellationTokenSource.Token), this.cancellationTokenSource.Token);
    }

    public override void OnStop()
    {
        this.cancellationTokenSource.Cancel();

        try
        {
            this.runTask.Wait();
        }
        catch (Exception e)
        {
            Logger.Error(e, e.Message);
        }

        base.OnStop();
    }

    // ... OnStart omitted
}

public static class Foo
{
    public static async Bar(CancellationToken token)
    {
        while (true)
        {
            try
            {
                token.ThrowIfCancellationRequested();

                var bar = await FooService.GetBar().ConfigureAwait(false);

                // Now token.IsCancellationRequested == true. Why? The above call does not take the token as input.
            }
            catch (OperationCanceledException)
            {
                // ... Handling
            }
        }
    }
}

我之前在另一个项目中成功使用了CancellationTokens,我在这里使用了类似的设置。我所知道的唯一区别是,这是在Azure云服务中。知道为什么IsCancellationRequested被设置为true?

1 个答案:

答案 0 :(得分:1)

在您等待OnStop完成时,系统会显示FooService.GetBar()。也许可以添加某种形式的日志记录,以查看OnStop之间以及token.ThrowIfCancellationRequested();返回确认后是否调用var bar = await ...

这就是导致令牌被取消的原因。

要解决此问题,您需要确保the overridden Run method does not return till the work is complete

public override void Run()
{
    this.cancellationTokenSource = new CancellationTokenSource();
    this.runTask = Task.Run(() => Foo.Bar(this.cancellationTokenSource.Token), this.cancellationTokenSource.Token);
    this.runTask.Wait(); //You may need a try/catch around it
}
相关问题