0

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.

Lunyx
  • 3,164
  • 6
  • 30
  • 46
  • Are these `Task`s from `System.Threading.Tasks`? – CodingGorilla Nov 16 '12 at 16:06
  • I am using `ThreadPool.QueueUserWorkItem(new WaitCallback(DoSomeWork), cts);` where cts is a `CancellationTokenSource` to call this method. – Lunyx Nov 16 '12 at 16:07
  • What is the 'event' you are referring in your question? I can see the 'DoSomeWork' method and then you are queueing work on the ThreadPool, but where are those events? – Adrian Ciura Nov 16 '12 at 16:13
  • First, I would suggest that you look into using Tasks, its a lot easier. But that aside, am I understanding that you launch 2 events, and then you launch a 3rd, but only want to cancel the first 2. Is that what you're asking? – CodingGorilla Nov 16 '12 at 16:14
  • @AdrianCiura, how is that relevant? @CodingGorilla, I launch the first event and the processing starts off. I then launch a second event which waits for the first to cancel, then starts processing. However, if I launch a third event before the second event starts, it processes both 2 and 3 when the first cancels. I want it to instead cancel 1, cancel 2, then start 3. I'll take a look into `Tasks`, but I do need to be able to do something along the lines of cancel 1 on object A, cancel 1 on object B, etc. There are multiple instances of this firing with a different parameter. – Lunyx Nov 16 '12 at 16:19

0 Answers0