当调用该方法的新实例时如何取消先前调用的方法

问题描述 投票:0回答:1

我有一个异步方法

Foo
,它会根据传入的事件在代码执行的各个点被调用。我需要一种方法来取消每当调用新实例时正在运行的此方法的任何线程/实例,有效“刷新”方法。

我考虑过将cancelTokenSource作为类变量。 我尝试了以下方法:

public static MyClass 
{
  static CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();

  public static async Task<Object> foo()
  {
    Object out = null;
    var previousTokenSource = Interlocked.Exchange(ref _cancellationTokenSource, new CancellationTokenSource());
    CancellationToken currentToken = _cancellationTokenSource.Token;
    try
    {
      previousTokenSource?.Cancel();

      await Task.Delay(1000, currentToken);
      out = ArbitraryLogic(currentToken)
    }
    catch (TaskCanceledException ex)
    {
      return null;
    }

    return out;
  }
}

所以如果我有测试功能:

public async void Test()
{
    var out1 = MyClass.foo();
    await Task.Delay(10);
    var out2 = MyClass.foo();

    await out1;
    await out2;
    if (out1.Result != null)
        Assert.Fail("out1.Result not null");
}

我希望

out1
为空,但目前不是。我究竟做错了什么?我该如何编写代码,在调用新方法时有效地停止方法的执行?

c# asynchronous cancellation cancellation-token cancellationtokensource
1个回答
0
投票

您问的是任务是否是

null
;你应该问结果是否是
null
:

var x = await out1;
var y = await out2;
Assert.IsNull(x); // fine
Assert.IsNotNull(y); // (depends on ArbitraryLogic)
© www.soinside.com 2019 - 2024. All rights reserved.