How to cancel await Task.Delay()?

后端 未结 4 754
生来不讨喜
生来不讨喜 2020-12-09 08:02

As you can see in this code:

public async void TaskDelayTest()
{
     while (LoopCheck)
     {
          for (int i = 0; i < 100; i++)
          {
                


        
4条回答
  •  醉梦人生
    2020-12-09 08:47

    Use the overload of Task.Delay which accepts a CancellationToken

    public async Task TaskDelayTest(CancellationToken token)
    {
        while (LoopCheck)
        {
            token.throwIfCancellationRequested();
            for (int i = 0; i < 100; i++)
            {
                textBox1.Text = i.ToString();
                await Task.Delay(1000, token);
            }
        }
    }
    
    var tokenSource = new CancellationTokenSource();
    TaskDelayTest(tokenSource.Token);
    ...
    tokenSource.Cancel();
    

提交回复
热议问题