c# - 立即退出 C# 中的 Parallel.For 循环

标签 c# .net multithreading .net-4.0 parallel-processing

在 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

有什么方法可以更快地做到这一点? 谢谢!

最佳答案

是的,这是可能的。看this详细介绍并行编程问题的文章。以下是其中的摘录:

What if I don’t want to waste resources and want to stop all computations immediately after I click Cancel? In this case, I have to periodically check for the status of the cancellation token somewhere within the method that performs the long-running operation. Since I declared the cancellation token as a field, I can simply use it within the method.

public double SumRootN(int root)
{
    double result = 0;
    for (int i = 1; i < 10000000; i++)
    {
        tokenSource.Token.ThrowIfCancellationRequested();
        result += Math.Exp(Math.Log(i) / root);
    }
    return result;
}

使用传统的 StopBreak 不会像您遇到的那样立即取消任务。根据this MSDN 上的文章,

In this context, "break" means complete all iterations on all threads that are prior to the current iteration on the current thread, and then exit the loop. "Stop" means to stop all iterations as soon as convenient.

所以你不能用传统的方法强制它立即停止。您将需要使用我在开头提到的方法。

希望对你有帮助!

关于c# - 立即退出 C# 中的 Parallel.For 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14720014/

相关文章:

c# - null 或空检查的代码优化

javascript - 如何在 MVC4 中添加按钮并重定向到另一个 View ?

c# - linux下C++中Gmap.Net的替代品

c# - 在第二部分和第三部分中输入低于 "An invalid IP address was specified"的数字时出现错误 "100"

c# - 创建嵌入式mysql数据库

c# - .NET DLL 中的 System.DllNotFoundException

c# - C#中的任务栈分配在哪里?

c - 带自旋锁的 pthreads 条件变量

c# - 如何以一种样式访问控件父级的属性

java - Double Check Lock 在此 java 代码上不起作用?