C# 使用配置的线程数执行工作的多线程代码
我想创建一个多线程应用程序代码。我想执行配置的线程数,每个线程都做这项工作。我想知道这是写方法还是我们有更好的方法。所有线程都需要异步执行C# 使用配置的线程数执行工作的多线程代码,c#,multithreading,C#,Multithreading,我想创建一个多线程应用程序代码。我想执行配置的线程数,每个线程都做这项工作。我想知道这是写方法还是我们有更好的方法。所有线程都需要异步执行 public static bool keepThreadsAlive = false; static void Main(string[] args) { Program pgm = new Program(); int noOfThreads = 4; keepThreadsAliv
public static bool keepThreadsAlive = false;
static void Main(string[] args)
{
Program pgm = new Program();
int noOfThreads = 4;
keepThreadsAlive = true;
for (int i = 1; i <= noOfThreads; i++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(DoWork), (object)i);
}
System.Console.ReadLine();
StopAllThreads();
System.Console.ReadLine();
}
private static void DoWork(object threadNumber)
{
int threadNum = (int)threadNumber;
int counter = 1;
while (keepThreadsAlive)
{
counter = ProcessACK(threadNum, counter);
}
}
private static int ProcessACK(int threadNum, int counter)
{
System.Console.WriteLine("Thread {0} count {1}", threadNum, counter++);
Random ran = new Random();
int randomNumber = ran.Next(5000, 100000);
for (int i = 0; i < randomNumber; i++) ;
Thread.Sleep(2000);
return counter;
}
公共静态bool keepThreadsAlive=false;
静态void Main(字符串[]参数)
{
程序pgm=新程序();
int noOfThreads=4;
keepThreadsAlive=true;
对于(inti=1;i,正如其他人所指出的,你所使用的方法已经过时了,而且没有更现代的C#方法来完成同样的任务那么优雅
请看一下,了解目前您可以使用的功能。甚至有一种方法可以设置并行操作中使用的最大线程数。下面是一个简单的(伪代码)示例:
希望这有帮助。查看.NET中的任务-多线程非常有帮助您可以这样做,但您选择了.NET平台上最古老的技术。调查TPL,特别是Parallel.ForEach和PLINQ。
Parallel.ForEach(someListOfItems, new ParallelOptions { MaxDegreeOfParallelism = 8 }, item =>
{
//do stuff for each item in "someListOfItems" using a maximum of 8 threads.
});