Use of IsCancellationRequested property?

前端 未结 1 456
渐次进展
渐次进展 2021-01-19 21:28

What is the use of CancellationToken\'s IsCancellationRequested property? Consider below code

static void Main(string[] args)
{
            


        
相关标签:
1条回答
  • 2021-01-19 21:47

    The problem with your code is that you don't wait for the Task to finish. So, what can happen is this:

    1. You call Cancel().
    2. You check Status, which returns Running.
    3. Confusingly, you write “Task completed” when the Task is still running.
    4. Main() completes, application exits.
    5. (At this point, IsCancellationRequested would be checked from the background thread. But that never happens, since the application already exited.)

    To fix that, add t.Wait() after you call Cancel().

    But that still won't fix your program completely. You need to tell the Task that it was canceled. And you do that by throwing OperationCanceledException that contains the CancellationToken (the usual way to do that is to call ThrowIfCancellationRequested()).

    One issue with that is that Wait()ing on a Task that was canceled will throw an exception, so you will have to catch that.

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