Yelhigh
Yelhigh

Reputation: 45

Break the Parallel ForEach from outside

Google didn't help me, SO neither.

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
    {

    }
});

I would like to break this ForEach loop after 5 seconds (in BreakEvent).

Of course it could be a button or anything.

I know about breaking by (in my example)

state.Stop();

But it's still inside the loop.

Is it even possible?

EDIT:

For everyone who search to the other way, I just though about it:

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

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

timer.Enabled = true;

Upvotes: 3

Views: 533

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186688

I suggest using cancellation:

// 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 
    }
}

Upvotes: 5

Related Questions