.net - Immediately exit a Parallel.For loop in c# -
in c#, possible exit parallel.for loop in progress. next code can take total sec exit loop after loopstate.stop() has been called.
static void main(string[] args) { stopwatch watch = new stopwatch(); parallel.for(0, 50, (i, loopstate) => { console.writeline("thread:" + thread.currentthread.managedthreadid + "\titeration:" + i); thread.sleep(1000); if (i == 0) { watch.start(); loopstate.stop(); return; } }); console.writeline("time elapsed since loopstate.stop(): {0}s", watch.elapsed.totalseconds); console.readkey(); }
output
thread:10 iteration:0 thread:6 iteration:12 thread:11 iteration:24 thread:12 iteration:36 thread:13 iteration:48 thread:13 iteration:49 thread:12 iteration:37 time elapsed since loopstate.stop(): 0.9999363s
is there way faster? thanks!
yes possible. @ this article goes detail parallel programming question. here excerpt out of it:
what if don’t want waste resources , want stop computations after click cancel? in case, have periodically check status of cancellation token somewhere within method performs long-running operation. since declared cancellation token field, can utilize within method.
public double sumrootn(int root) { double result = 0; (int = 1; < 10000000; i++) { tokensource.token.throwifcancellationrequested(); result += math.exp(math.log(i) / root); } homecoming result; }
using traditional stop
or break
not cause task canceled immediately, experiencing. according this article on msdn,
in context, "break" means finish iterations on threads prior current iteration on current thread, , exit loop. "stop" means stop iterations convenient.
so can't forcefulness stop using traditional method. need utilize method mentioned @ beginning.
hope helps you!
c# .net multithreading .net-4.0 parallel-processing
No comments:
Post a Comment