Answer the question
In order to leave comments, you need to log in
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);
}
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question