I have some code I want to run until I request cancellation.
Task.Run(() =>
{
while (!token.IsCancellationRequested)
{
GetFeedbackTask();
}
}, token);
I then execute this method token.Cancel()
. This cancels the task as expected and my while loop as expected. The problem is when I try to run the Task again after I cancel the token.IsCancellationRequested
property is still true
. What sets the property back to false
? Do I need to Dispose
the token?
You can't ever set a CancellationToken
from a cancelled state back into a non-cancelled state.
Likewise, the Task
that you've created to do work will have ended; it's not just going to sit there waiting once the token is cancelled. The while
loop will have ended, and as there is no more code the task will be completed.
If you want to re-start the work after having cancelled it start a new worker and create a new cancellation token.