打破Parallel.ForEach循环的外部控制

3

Google没有帮助到我,Stack Overflow也没有。

var timer = new System.Timers.Timer(5000);
timer.Elapsed += BreakEvent;
timer.Enabled = true;

Parallel.ForEach<string>(fileNames, (fileName, state) =>
{
    try
    {
        ProcessFile(fileName);
    }
    catch (Exception)
    {

    }
    finally
    {

    }
});

我希望在5秒钟后(在BreakEvent中)中断这个ForEach循环。
当然,它可以是一个按钮或其他任何东西。
我知道如何通过(在我的示例中)来中断。
state.Stop();

但它仍然在循环内部。

这是否可能呢?

编辑:

对于所有搜索其他方式的人,我刚想到:

var timer = new System.Timers.Timer(5000);

timer.Elapsed += new System.Timers.ElapsedEventHandler((obj, args) =>
{
    state.Stop();
});

timer.Enabled = true;

相关问题 - stuartd
@MassimilianoKraus,这是我最初的想法,但这个问题涉及从循环“内部”中断,而不是从外部中断。 - stuartd
是的,这一切都是关于从内部打破的。 - Yelhigh
1个回答

5

我建议使用取消

// Cancel after 5 seconds (5000 ms)
using (var cts = new CancellationTokenSource(5000))
{
    var po = new ParallelOptions()
    {
        CancellationToken = cts.Token,
    };

    try
    {
        Parallel.ForEach(fileNames, po, (fileName) =>
        {
            //TODO: put relevant code here
        });
    }
    catch (OperationCanceledException e)
    {
        //TODO: Cancelled 
    }
}

哦,这是个好主意! :) 我没有想到,谢谢你! - Yelhigh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接