如果用户按“c”键,则中断Parallel.ForEach

时间:2018-04-23 13:03:26

标签: c# console-application

如果用户按'c',则Parallel.ForEach应该在不取消已启动任务的情况下中断。现在我的程序正在等待用户,我怎么能这样做,用户可以随时写'c',程序将在启动任务完成后取消?

List<int> companies = new List<int> { 56, 1, 18, 26, 37, 45, 47, 50, 56, 60 };
Parallel.ForEach(companies, (company, state) =>
{
    if (Console.ReadKey().KeyChar == 'c')
    {
        state.Break();
    }

    MyFunction(company);
});

编辑 - 最终解决方案:

try
{
    List<int> companies = new List<int> { 78, 1, 18, 26, 37, 45, 47, 50, 56, 60 };
    CancellationTokenSource cts = new CancellationTokenSource();
    ParallelOptions po = new ParallelOptions();
    po.CancellationToken = cts.Token;

    Task.Factory.StartNew(() =>
    {
        if (Console.ReadKey().KeyChar == 'c')
        {
            cts.Cancel();
        }
    });

    Parallel.ForEach(companies, (company, state) =>
    {
        MyFunction(company);

        po.CancellationToken.ThrowIfCancellationRequested();
    });
}
catch (OperationCanceledException ex)
{
    Console.WriteLine("Cancelled program");
}

1 个答案:

答案 0 :(得分:2)

您的Console.ReadKey方法调用不应该在Parallel.ForEach内,而应该在它之后。

然后,使用该读取键取消foreach,使用CancellationToken。

请参阅:https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/how-to-cancel-a-parallel-for-or-foreach-loop