Smash the parallel ForEach system outside

Google didn't help me, and it doesn't.

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 loop ForEach

after 5 seconds (in BreakEvent

).

Of course, it could be a button or something else.

I am aware of the violation (in my example)

state.Stop();

      

But he's still inside the loop.

Is it possible?

EDIT:

For anyone looking differently, I'm just about this:

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

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

timer.Enabled = true;

      

+3


source to share


1 answer


I suggest using undo:



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

      

+5


source







All Articles