Cancel ONLY one task with CancellationToken

Lets assume that we have a Producer-Consumer pattern created with One Producing Task and 3 Consumer Tasks as follow:

        Task[] Consumer = new Task[10];
        for (int i = 0; i < 3; i++)
        {

            Consumer[i] = Task.Run(() => DoWork(CancellationToken ct));
        }

the question is how can I ONLY cancel Task Consumer[2]? when a cancellationtoken is sent all the Consumers stop! I want to have the ability to cancel a single Consumer if needed.

Many thanks

Jon Skeet
people
quotationmark

If you need to cancel all the consumers independently, you need separate cancellation tokens - and thus separate cancellation token sources.

var consumers =
    Enumerable
        .Range(0, 10)
        .Select(_ => new CancellationTokenSource())
        .Select(cts => new { Task = Task.Run(() => DoWork(cts.Token)),
                             TokenSource = cts })
        .ToList();

That will gives you a List<T> where each element is the task and its corresponding CancellationTokenSource. So if you wanted to cancel consumers[0].Task, you'd call consumers[0].TokenSource.Cancel().

people

See more on this question at Stackoverflow