TPL - Parallel with Cancellation token

Scenario:

Process data in parallel and on trigger cancel it in between

Solution:

MSDN: In a parallel loop, you supply the CancellationToken to the method in the ParallelOptions parameter and then enclose the parallel call in a try-catch block.

Create a CancelToken and and register it with a Parallel.ForEach. Create another thread and on trigger using this CancelToken it cancels the foreach processing.
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    public class ParallelWithCancellation
        {
            static void Main(string[] args)
            {
                int[] count = Enumerable.Range(0, 1000).ToArray();
    
                CancellationTokenSource cts = new CancellationTokenSource();
    
                ParallelOptions options = new ParallelOptions
                {
                    CancellationToken = cts.Token,
                    MaxDegreeOfParallelism = Environment.ProcessorCount
                };
    
                Console.WriteLine("Press key to start or e to cancel");
                Console.ReadKey();
    
                //Cancel on Trigger the operations which has the Cancel Token
                Task.Factory.StartNew(() =>
                {
                    if (Console.ReadKey().KeyChar == 'e')
                        cts.Cancel();
                    Console.WriteLine("Canceled");
                });
    
                try
                {
                    //Register the Cancel token
                    Parallel.ForEach(count, options, (c) =>
                    {
                        Console.WriteLine("{0} on {1}", c, Thread.CurrentThread.ManagedThreadId);
                        options.CancellationToken.ThrowIfCancellationRequested();
                    });
                }
                catch (OperationCanceledException e)
                {
                    Console.WriteLine(e.Message);
                }
                finally
                {
                    cts.Dispose();
                }
    
                Console.ReadLine();
            }
        }

No comments:

Post a Comment

Move Github Sub Repository back to main repo

 -- delete .gitmodules git rm --cached MyProject/Core git commit -m 'Remove myproject_core submodule' rm -rf MyProject/Core git remo...