什么是取消在C#中多个任务的正确方法 [英] what is the correct way to cancel multiple tasks in c#

查看:487
本文介绍了什么是取消在C#中多个任务的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个按钮,这就是滋生4个任务。同样的按钮变为取消按钮,点击这个应该取消所有4个任务。我应该传递相同的取消标记所有4个任务,让他们对IsCancelRequested同样民意调查?我读的 createlinkedtokensource 在MSDN文档后混淆。这是如何正常执行?谢谢

I have a button thats spawns 4 tasks. The same button changes to a cancel button and clicking this should cancel all 4 tasks. Should I pass the same cancel token to all 4 tasks and have them poll on the same token for IsCancelRequested ? I am confused after reading the msdn doc on createlinkedtokensource. How is this normally done ? thank you

更新:Task.WaitAll()等待耕种的所有任务完成执行。同样如何知道什么时候所有的任务都被取消一旦共享取消标记源设置为取消。

Update: Task.WaitAll() waits tills all tasks complete execution. Similarly how to know when all tasks have been canceled once the shared cancel token source is set to cancel.

推荐答案

是啊,你说的关于使用单个的CancellationToken 是正确的。您可以创建一个 CancellationTokenSource ,并使用其的CancellationToken 所有的任务。你的任务,应定期检查令牌注销

Yeah, what you said about using a single CancellationToken is correct. You can create a single CancellationTokenSource and use its CancellationToken for all of the tasks. Your tasks should check the token regularly for cancellation.

例如:

const int NUM_TASKS = 4;

CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken ct = cts.Token;

Task[] tasks = new Task[NUM_TASKS];
for (int i = 0; i < NUM_TASKS; i++)
{
    tasks[i] = Task.Factory.StartNew(() =>
    {
        while (true)
        {
            Thread.Sleep(1000);
            if (ct.IsCancellationRequested)
                break;
        }
    }, ct);
}

Task.WaitAll(tasks);

您的按钮调 cts.Cancel(); 取消任务

更新问题更新:

有有几个方法可以做到你的要求。一种方法是使用 ct.IsCancellationRequested 来检查取消不抛出,然后让你的任务来完成。然后 Task.WaitAll(任务)将完成当所有的任务都被取消。

There are a few ways to do what you ask. One way is to use ct.IsCancellationRequested to check cancellation without throwing, then allow your task to complete. Then Task.WaitAll(tasks) will complete when all of the tasks have been cancelled.

我已经更新了代码,以反映这种变化。

I've updated the code to reflect that change.

这篇关于什么是取消在C#中多个任务的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆