C# 在循环中使用C中的ThreadPool并等待所有线程完成
我有一个简单的代码,在C语言中是这样的:C# 在循环中使用C中的ThreadPool并等待所有线程完成,c#,threadpool,C#,Threadpool,我有一个简单的代码,在C语言中是这样的: using System; using System.Threading; using System.Diagnostics; namespace ThreadPooling { class Program { static void Main(string[] args) { Console.WriteLine("Enter the number of calculation
using System;
using System.Threading;
using System.Diagnostics;
namespace ThreadPooling
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the number of calculations to be made:");
int calculations= Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Thread Pool Execution");
for (int i = 1; i <= calculations; i++)
{
Console.WriteLine("Staring process " + i + "...");
ThreadPool.QueueUserWorkItem(new WaitCallback(Process(i)));
}
Console.WriteLine("All calculations done.");
Console.WriteLine("\nPress any key to exit the program...");
Console.ReadKey();
}
static void Process(object callback, int name)
{
for (int i = 0; i <= 10; i++)
{
Console.WriteLine(i + " is the current number in " + name);
}
}
}
}
我希望main能够使用线程池和参数调用进程。然后,我希望程序在告诉用户它已经完成之前,等待所有线程完成。我如何做到两者?似乎我不能在进程内放置参数,我得到:错误CS7036没有给定与“Program.Processobject,int”的必需形式参数“name”对应的参数
我也不清楚如何告诉C等待循环中的所有进程完成,然后再告诉用户它已经完成了。.NET已经有将近20年的历史了,并且有几代改进的API 这对于较新的方法来说是微不足道的。乙二醇
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace ThreadPooling
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the number of calculations to be made:");
int calculations = Convert.ToInt32(Console.ReadLine());
var tasks = new List<Task>();
for (int i = 1; i <= calculations; i++)
{
int processNum = i;
Console.WriteLine("Staring process " + processNum + "...");
var task = Task.Run(() => Process(processNum));
tasks.Add(task);
}
Task.WaitAll(tasks.ToArray());
Console.WriteLine("All calculations done.");
Console.WriteLine("\nPress any key to exit the program...");
Console.ReadKey();
}
static void Process(int name)
{
for (int i = 0; i <= 10; i++)
{
Console.WriteLine(i + " is the current number in " + name);
}
}
}
}
您的方法进程接受两个参数,object和int,但当您调用它时,您只传递了一个参数。尝试ThreadPool.QueueUserWorkItem=>Processi,i;谢谢你的作品!另一方面,C++是否也有线程池?C++中没有内置的,但Windows确实有。NET QueueUserWorkItem API就是受此启发而来的。见示例: