如何取消任务类型集合中的特定任务

所以我想找出一种方法来取消特定任务。在示例中,我想取消它生成的 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,我该怎么做?


拉丁的传说
浏览 58回答 1
1回答

SMILET

CancellationToken如果你想单独取消它们,你需要为你开始的每个任务传递一个:static async Task Main(string[] args){&nbsp; &nbsp; var cancellationSources = Enumerable.Range(0, 3)&nbsp; &nbsp; &nbsp; .Select(_ => new CancellationTokenSource())&nbsp; &nbsp; &nbsp; .ToList();&nbsp; &nbsp; var tasks = Enumerable.Range(0, 3).Select(x => Task.Run(&nbsp; &nbsp; &nbsp; &nbsp; () => Counter(cancellationSources[x].Token),&nbsp; &nbsp; &nbsp; &nbsp; cancellationSources[x].Token&nbsp; &nbsp; ));&nbsp; &nbsp; cancellationSources[1].Cancel();&nbsp; &nbsp; await Task.WhenAll(tasks);&nbsp; &nbsp; Console.ReadLine();}public static void Counter(CancellationToken cancellationToken){&nbsp; &nbsp; while (!cancellationToken.IsCancellationRequested)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // or while(true) and token.ThrowIfCancellationRequested(); to throw instead&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < 1000; i++)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine(i);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP