简体   繁体   中英

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

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM