作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
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/
我是一名优秀的程序员,十分优秀!