O
O
oleg_ods2022-04-02 00:00:19
C++ / C#
oleg_ods, 2022-04-02 00:00:19

Why is the CreateLinkedTokenSource(CancellationToken) method needed?

Why is the CreateLinkedTokenSource(CancellationToken) method needed? The question is about overloading the method with one CancellationToken parameter. I understand that this is an opportunity to create a chain of methods that should be interrupted completely when requesting cancellation from one token. But why then not pass one token to all methods of the chain?

For example,

static void Main(string[] args)
        {
            var ctx = new CancellationTokenSource();

            var task = FirstMethodAsync(ctx.Token);
            //var task = FirstMethodLinkedAsync(ctx.Token); // Результат идентичен вызову метода FirstMethodAsync.

            ConsoleKeyInfo key;

            while (!task.IsCompleted)
            {                
                key = Console.ReadKey();

                if (key.KeyChar == 'e')
                {
                    ctx.Cancel();                    
                }
            }

            Console.WriteLine("Good buy!");
        }

        static async Task FirstMethodAsync(CancellationToken cancellationToken)
        {
            var secondTask = SecondMethodAsync(cancellationToken);
            while (true)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    Console.WriteLine("First method cancelled");
                    return;
                }
                Console.WriteLine("First method: {0}", DateTime.Now.ToLongTimeString());
                await Task.Delay(500);
            }
        }

        static async Task FirstMethodLinkedAsync(CancellationToken cancellationToken)
        {
            var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
            var secondTask = SecondMethodAsync(cts.Token);
            while (true)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    Console.WriteLine("First method cancelled");
                    return;
                }
                Console.WriteLine("First method: {0}", DateTime.Now.ToLongTimeString());
                await Task.Delay(500);
            }
        }

        static async Task SecondMethodAsync(CancellationToken cancellationToken)
        {
            while (true)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    Console.WriteLine("Second method cancelled");
                    return;
                }
                Console.WriteLine("Second method: {0}", DateTime.Now.ToLongTimeString());
                await Task.Delay(750);
            }
        }


The results of both calls, in my opinion, are identical. Why then create another CancellationTokenSource if you can just pass the finished CancellationToken to the next method?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2022-04-02
@oleg_ods

I'm not sure when exactly this might be needed in real life (I didn't have such a need myself), but for example
: first CancellationToken
2. You create your own CTS and link it to the first token.
Profit, the task is solved - your method can be canceled both from the outside and for some internal reasons.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question