简体   繁体   English

C#DataFlow:等待ConcurrentExclusiveSchedulerPair启动的所有任务完成

[英]C# DataFlow: Wait for all tasks started by ConcurrentExclusiveSchedulerPair to finish

I have a list of operations to be executed, and can be cancelled on user interaction. 我有一个要执行的操作列表,可以在用户交互时取消。 Pretty simple, but ConcurrentExclusiveSchedulerPair .Completion is never finishing. 很简单,但是ConcurrentExclusiveSchedulerPair .Completion 。完成从未完成。 Here's an example: 这是一个例子:

static void Main(string[] args)
{
    var taskSchedulerPair = new ConcurrentExclusiveSchedulerPair();
    var cts = new CancellationTokenSource();
    var optiions = new ExecutionDataflowBlockOptions
    {
        TaskScheduler = taskSchedulerPair.ConcurrentScheduler,
        CancellationToken = cts.Token,
        MaxDegreeOfParallelism = 5
    };
    var a1 = new ActionBlock<int>(new Func<int, Task<int>>(Moo), optiions);
    for (var i = 0; i < 20; i++) a1.Post(i);
    Console.WriteLine("Press any key to cancel...");
    Console.ReadKey(false);
    Console.WriteLine("Cancelling...");
    cts.Cancel();
    // taskSchedulerPair.Complete();
    taskSchedulerPair.Completion.Wait();
    // This never prints
    Console.WriteLine("Done.");
    Console.ReadKey(false);
}

public static async Task<int> Moo(int ms)
{
    Console.WriteLine("Starting: " + ms);
    await Task.Delay(4000);
    Console.WriteLine("Ending" + ms);
    return ms + 100;
}

From the docs 来自文档

Calling Complete is optional. 调用完成是可选的。 It is necessary only if you're relying on the Completion property for notification that all processing has been complete . 仅当您依赖Completion属性通知所有处理已完成时,才有必要

So if you want to Wait on the Completion property then you have to call Complete() on the scheduler. 因此,如果要在Completion属性上Wait ,则必须在调度程序上调用Complete() This behavior is the same for a data flow block; 对于数据流块,此行为相同。 to rely on the Completion property you have to call Complete() on the block. 依赖于Completion属性,你必须在块上调用Complete()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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