Let's say we have an event that triggers the following method:
public static void DoSomeWork(object obj)
{
CancellationTokenSource cts = (CancellationTokenSource)obj;
if (cts.IsCancellationRequested)
return;
Console.WriteLine("Started thread {0}.", Name);
for (int i = 0; i < 3; i++)
{
Console.WriteLine("Working on thread {0} at step {1}.", Name, i);
Thread.Sleep(10000);
if (cts.IsCancellationRequested)
{
Console.WriteLine("Canceled thread {0} at step {1}.", Name, i);
return;
}
}
Console.WriteLine("Completed thread {0}.", Name);
}
You can ignore the Name
variable as the original object is something that contains the name as a string and a CancellationTokenSource
. From what I understand, I can use ManualResetEvent.WaitOne()
to wait for the cancellation to finish if I call ManualResetEvent.Set()
after detecting that cts.IsCancellationRequested == true
. This seems to work fine if I have only one new event to be processed. However, if I trigger this event multiple times while the current process is canceling, it now runs both events simultaneously instead. The desired result is that all events prior to the most recent event are canceled and the processing runs on the most recent event.
How can I make this work? Am I on the right track? Let me know if there's any additional information that I can provide that can assist in answering this question.