c# - 使用 Task.WaitAll(threads) 没有适本地阻塞

标签 c# multithreading

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Threads
{
    class Program
    {
        static void Main(string[] args)
        {
            Action<int> TestingDelegate = (x321) => { Console.WriteLine(x321); };
            int x123 = Environment.ProcessorCount;

            MyParallelFor(0, 8, TestingDelegate);
            Console.Read();
        }

        public static void MyParallelFor(int inclusiveLowerBound, int exclusiveUpperBound, Action<int> body)
        {

            int size = exclusiveUpperBound - inclusiveLowerBound;
            int numProcs = Environment.ProcessorCount;
            int range = size / numProcs;

            var threads = new List<Task>(numProcs);
            for(int p = 0; p < numProcs; p++)
            {
                int start = p * range + inclusiveLowerBound;
                int end = (p == numProcs - 1) ? exclusiveUpperBound : start + range;
                Task.Factory.StartNew(() =>
                {
                    for (int i = start; i < end; i++) body(i);
                });

            }

            Task.WaitAll(threads.ToArray());
            Console.WriteLine("Done!");
        }
    }
}

大家好,我从并行编程模式一书中实现了这段代码,他们使用线程来实现,我决定使用 TPL 库重写它。下面的输出是我得到的(当然它是随机的)但是......我希望“完成!”总是最后打印。出于某种原因,它并没有这样做。为什么不阻塞?

Done!
1
0
2
6
5
4
3
7

最佳答案

您没有向调用 WaitAll 的 threads 列表分配任何任务,您的任务是独立启动的。在调用 WaitAll 之前,您将创建任务并将任务放入 threads 集合中。您可以在本 MSDN 文档中为 Task.WaitAll Method (Task[]) 找到更多如何在任务列表中添加任务的信息。

你的代码应该是这样的

threads.Add(Task.Factory.StartNew(() =>
{
    for (int i = 0; i < 10; i++) ;
}));

关于c# - 使用 Task.WaitAll(threads) 没有适本地阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35330699/

相关文章:

c# - 我应该如何覆盖 DbContext 上的 SaveChanges() 方法,以便使用 EF 4.3 维护已删除/修改的记录?

c# - 如何在打印 PDF 时设置打印机设置

Java 线程安全计数器

java - 当 JPanel.repaint() 不调用 PaintComponent 时如何修复//我发现没有任何工作

c++ - 在循环中更新 Qt GUI(将位图图像显示为电影)

c++ - 与 kill 一起发送到父线程的信号是否保证在下一条语句之前得到处理?

c# - 使用非静态方法的线程

c# - 阻止 ReSharper 添加注释

c# - 如何在Unity中创建简单的FirstPersonController : Compiler ERROR messages?

c# - Azure DocumentDB,使用 LINQ 在字典中搜索