【问题标题】:How do I cancel a specific task in a collection of type Task如何取消任务类型集合中的特定任务
【发布时间】:2019-04-25 23:13:11
【问题描述】:

所以我想找出一种方法来取消特定任务。 在示例中,我想取消它产生的 3 个任务中的 2 个

static async Task Main(string[] args)
{

    var tasks = Enumerable.Range(0, 3).Select(x => Task.Run(() =>
    {
        Counter();
    }));



    await Task.WhenAll(tasks);

    Console.ReadLine();

}

public static void Counter()
{
    while (true)
    {
        for (int i = 0; i < 1000; i++)
        {
            Console.WriteLine(i);
        }
    }
}

如果我要执行while (someProperty) 并将someProperty 更改为false,那么所有线程都会停止。我想停2/3,怎么办?

【问题讨论】:

  • 无法真正取消任务。我想你可以中止一个线程,但这通常是一个非常糟糕的主意。您需要在Counter() 方法中编写逻辑,以在满足条件时使循环退出。然后,您通过设置该条件“结束”任务,使其退出循环。例如,您可以使用while (flag == true) 并在主代码中设置flag,而不是while (true)

标签: c# .net multithreading task


【解决方案1】:

如果你想单独取消它们,你需要为你开始的每个任务传递一个CancellationToken

static async Task Main(string[] args)
{
    var cancellationSources = Enumerable.Range(0, 3)
      .Select(_ => new CancellationTokenSource())
      .ToList();

    var tasks = Enumerable.Range(0, 3).Select(x => Task.Run(
        () => Counter(cancellationSources[x].Token),
        cancellationSources[x].Token
    ));

    cancellationSources[1].Cancel();

    await Task.WhenAll(tasks);

    Console.ReadLine();

}

public static void Counter(CancellationToken cancellationToken)
{
    while (!cancellationToken.IsCancellationRequested)
    {
        // or while(true) and token.ThrowIfCancellationRequested(); to throw instead

        for (int i = 0; i < 1000; i++)
        {
            Console.WriteLine(i);
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-30
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    • 1970-01-01
    • 1970-01-01
    • 2016-12-27
    • 1970-01-01
    相关资源
    最近更新 更多