Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I think the best solution is "<strong>Parallel Foreach Cancellation</strong>". Please check the following code.</p> <ol> <li>To implement a cancellation, you first make <code>CancellationTokenSource</code> and pass it to <code>Parallel.ForEach</code> through <code>option</code>.</li> <li>If you want to cancel, you can call <code>CancellationTokenSource.Cancel()</code></li> <li>After the cancelling, OperationCanceledException will be occurred, which you need to handle.</li> </ol> <p>There is a good article about <code>Parallel Programming</code> related to my answer, which is <strong><a href="http://www.codeproject.com/KB/cs/TPL1.aspx" rel="nofollow">Task Parallel Library By Sacha Barber on CodeProject</a></strong>.</p> <pre><code>CancellationTokenSource tokenSource = new CancellationTokenSource(); ParallelOptions options = new ParallelOptions() { CancellationToken = tokenSource.Token }; List&lt;string&gt; urlList = null; //parallel foreach cancellation try { ParallelLoopResult result = Parallel.ForEach(urlList, options, (url) =&gt; { // Create the thread object. This does not start the thread. Worker workerObject = new Worker(); workerObject.DoWork(url); }); } catch (OperationCanceledException ex) { Console.WriteLine("Operation Cancelled"); } </code></pre> <hr> <p><strong>UPDATED</strong> </p> <p>The following code is "Parallel Foreach Cancellation Sample Code".</p> <pre><code>class Program { static void Main(string[] args) { List&lt;int&gt; data = ParallelEnumerable.Range(1, 10000).ToList(); CancellationTokenSource tokenSource = new CancellationTokenSource(); Task cancelTask = Task.Factory.StartNew(() =&gt; { Thread.Sleep(1000); tokenSource.Cancel(); }); ParallelOptions options = new ParallelOptions() { CancellationToken = tokenSource.Token }; //parallel foreach cancellation try { Parallel.ForEach(data,options, (x, state) =&gt; { Console.WriteLine(x); Thread.Sleep(100); }); } catch (OperationCanceledException ex) { Console.WriteLine("Operation Cancelled"); } Console.ReadLine(); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload