How to cancel await Task.Delay()?

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

    Just a slight comment about having a cancellation token, and using a try-catch to stop it throwing an exception - your iteration block might fail due to a different reason, or it might fail due to a different task getting cancelled (e.g. from an http request timing out in a sub method), so to have the cancellation token not throw an exception you might want a bit more complicated catch block

    public async void TaskDelayTest(CancellationToken token)
    {
        while (!token.IsCancellationRequested)
        {
            for (int i = 0; i < 100; i++)
            {
                try
                {
                    textBox1.Text = i.ToString();
                    await DoSomethingThatMightFail();
                    await Task.Delay(1000, token);
                }
                catch (OperationCanceledException) when (token.IsCancellationRequested)
                {
                    //task is cancelled, return or do something else
                    return;
                }
                catch(Exception ex)
                {
                     //this is an actual error, log/throw/dostuff here
                }
            }
        }
    }
    

提交回复
热议问题