gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:36:19 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com