Created
March 8, 2017 13:53
-
-
Save miteshsureja/2a68c6edd7959aeb55c71f01f195b5a7 to your computer and use it in GitHub Desktop.
How to cancel a Parallel.For and Parallel.Foreach loop – Task Parallel Library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using System.Diagnostics; | |
using System.Linq; | |
using System.Text; | |
using System; | |
using System.Threading.Tasks; | |
using System.Threading; | |
namespace ParallelFor | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
using (CancellationTokenSource cancelToken = new CancellationTokenSource()) | |
{ | |
//Setting cancellationtoken to parallel options | |
ParallelOptions options = new ParallelOptions(); | |
options.CancellationToken = cancelToken.Token; | |
Console.WriteLine("Press 'c' to cancel."); | |
//running another thread to get user cancel request | |
Task.Factory.StartNew(() => | |
{ | |
if (Console.ReadKey().KeyChar == 'c') | |
cancelToken.Cancel(); | |
}); | |
try | |
{ | |
Console.Write("Starting Parallel.For loop"); | |
Parallel.For(0, 100000, options, (i) => | |
{ | |
Console.Write("{0}, ", i); | |
options.CancellationToken.ThrowIfCancellationRequested(); | |
}); | |
} | |
catch (OperationCanceledException ex) | |
{ | |
Console.ForegroundColor = ConsoleColor.Red; | |
Console.WriteLine("Parallel loop has been canceled by user"); | |
} | |
catch (Exception e) | |
{ | |
throw (e); | |
} | |
} | |
Console.ReadLine(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to cancel a Parallel.For and Parallel.Foreach loop – Task Parallel Library