Why does my task not cancel?

后端 未结 1 1307
后悔当初
后悔当初 2021-01-24 04:44

I\'m running a process that periodically Curls to a list of URLs to test out performance to those websites. My main program is basically a do...sleep...while loop that calls a f

相关标签:
1条回答
  • 2021-01-24 04:53

    There is no automatism in cancellation. You have to check for the cancellation status and end your execution or invoke CancellationToken.ThrowIfCancellationRequested to perform the cancellation. The CancellationToken will tell you if cancellation is requested; the cancellation itself has to be done by you.

    The following line is your problem:

    Task t = new Task(() => easy.Perform(), cts.Token);
    

    You are passing the token to the task constructor. That will help you if your cancellation occurs before the task is started. Once the task is started, the executed method is responsible for cancellation. easy.Perform() does not know about your cancellation token and therefore will never be able to determine if cancellation is requested. Hence, it will run to its end.

    You need to regularly check your cancellation token during task execution to achieve what you want.

    0 讨论(0)
提交回复
热议问题