How to cancel await Task.Delay()?

后端 未结 4 768
生来不讨喜
生来不讨喜 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

    If you're going to poll, poll on a CancellationToken:

    public async Task TaskDelayTestAsync(CancellationToken token)
    {
      for (int i = 0; i < 100; i++)
      {
        textBox1.Text = i.ToString();
        await Task.Delay(TimeSpan.FromSeconds(1), token);
      }
    }
    

    For more information, see the cancellation documentation.

提交回复
热议问题