如果用户按'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");
}
答案 0 :(得分:2)
您的Console.ReadKey
方法调用不应该在Parallel.ForEach
内,而应该在它之后。
然后,使用该读取键取消foreach,使用CancellationToken。