Break Parallel Foreach Earlier

Break Parallel Foreach Earlier

Use the ParallelLoopState.Break or ParallelLoopState.Stop method to end parallel foreach loop:

public void BreakParallelForeachEarlier()
{
    var list = new List<Int32>();
    for (var i = 0; i < 100; ++i)
        list.Add(i);

    var startTime = DateTime.Now;
    var maxRunTimeInMs = 2500;

    Parallel.ForEach(list, (elem, state) =>
    {
        Console.WriteLine("Running for {0}", elem);
        Thread.Sleep(1000 + elem); // Running exhausting algorithm

        var duration = (DateTime.Now - startTime).TotalMilliseconds;
        if (duration > maxRunTimeInMs)
        {
            Console.WriteLine("Exiting the parallel foreach block...");
            state.Break();
        }
    });
}


Break Parallel Foreach Earlier
added 9 years 7 months ago

- How to make bold the text before colon character in Microsoft Word
- Generate object from xml in c#
- 24 Useful Distinct Color Codes
- How to draw an arrow with DrawLine command
- How to write Snake game in C#?
- Break Parallel Foreach Earlier
- How to find all Stored Procedures having a given text inside
- How to Create and Write Excel File in C#
- Extension Methods
- Microsoft Code Contracts
- VersaFix
- QuickFIX
- fix4net
- Converting String to Double in C#
- C# File Operations, C# Input Output (C# I/O)
2
1