Home > Software engineering >  CancellationToken.Register(MyMethod). In what cases the method may not be called Methods execution o
CancellationToken.Register(MyMethod). In what cases the method may not be called Methods execution o

Time:12-03

In book Microsoft Visual C # Step by Step Ninth Edition John Sharp said:

You can also register a callback method (in the form of an Action delegate) with the cancellation token by using the Register method. When an application invokes the Cancel method of the corresponding CancellationTokenSource object, this callback runs. However, you cannot guarantee when this method executes; it might be before or after the tasks have performed their own cancellation processing, or even during that process.

cancellationToken.Register(doAdditionalWork);

private void doAdditionalWork() { // Perform additional cancellation processing }

It's all.

First question. I do not understand how this can be. Can someone give an example when a method is registered, the token is canceled, but for some reason the method that is registered has not been executed?

Second question. The order of method calls. It is reverse. Why? Inside a stack of delegates??

using System;
using System.Threading;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            void MyMethod(int a)
            {
                Console.WriteLine(a);
            }

            CancellationTokenSource MyCancellationTokenSource = new CancellationTokenSource();
            CancellationToken MyCancellationToken = MyCancellationTokenSource.Token;

            MyCancellationToken.Register(() => MyMethod(1));
            MyCancellationToken.Register(() => MyMethod(2));
            MyCancellationToken.Register(() => MyMethod(3));

            MyCancellationTokenSource.Cancel();

            //Console:
            //3
            //2
            //1
        }
    }
}

CodePudding user response:

Keep in mind that execution order in multi threaded systems is not well defined. A thread may be suspended at any time for theoretically any length of time. Ordering is only guaranteed within a thread. For example the following could happen

  1. Cancel is called on thread A
  2. MyMethod is queued to run (thread A)
  3. Cancel token is marked as canceled (thread A)
  4. The task checks the token, observes that it is cancelled, and aborts (thread B)
  5. Scheduler gets around to calling MyMethod on thread C

It is unclear to me if there are any case where MyMethod would never run. The documentation for CancellationToken.Register states:

Registers a delegate that will be called when this CancellationToken is canceled.

and

If this token is already in the canceled state, the delegate will be run immediately and synchronously.

So I would assume that the registered method will always be called if the token is, or will be, canceled. But you cannot assume anything about when this it is done.

  • Related