在 C# 中,是否可以立即退出正在进行的 Parallel.For 循环。在调用 loopState.Stop() 之后,以下代码可能需要一整秒才能退出循环。
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();
}
输出
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
有什么办法可以更快地做到这一点?谢谢!