在 c# 中动态运行多个线程

本文关键字:线程 运行 动态 | 更新日期: 2023-09-27 17:56:09

>我有一个程序,我需要同时运行多个线程

int defaultMaxworkerThreads = 0;
int defaultmaxIOThreads = 0;
ThreadPool.GetMaxThreads(out defaultMaxworkerThreads, out defaultmaxIOThreads);
ThreadPool.SetMaxThreads(defaultMaxworkerThreads, defaultmaxIOThreads);
List<Data1> Data1 = PasswordFileHandler.ReadPasswordFile("Data1.txt");
List<Data1> Data2 = PasswordFileHandler.ReadPasswordFile("Data2.txt");
while (Data1.Count >= 0)
{
    List<String> Data1Subset = (from sub in Data1 select sub).Take(NumberOfWordPrThead).ToList();
   Data1 = _Data1.Except(Data1Subset ).ToList();
   _NumberOfTheadsRunning++;
   ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadCompleted), new TaskInfo(Data1Subset , Data2 ));
    //Start theads based on how many we like to start
}

如何一次运行多个线程?我想根据内核数和配置设置在运行时决定线程数,但我的代码似乎总是只运行一个线程。

我应该如何更改它以在多个线程上运行?

在 c# 中动态运行多个线程

正如@TomTom所指出的,如果你同时设置了SetMinThreads和SetMaxThreads,你的代码将正常工作。根据 MSDN,您还必须注意不要在执行线程池之前过早退出主线程:

// used to simulate different work time
static Random random = new Random();
// worker
static private void callback(Object data) 
{
   Console.WriteLine(String.Format("Called from {0}", data));
   System.Threading.Thread.Sleep(random.Next(100, 1000));
}
//
int minWorker, minIOC;
ThreadPool.GetMinThreads(out minWorker, out minIOC);
ThreadPool.SetMaxThreads(5, minIOC);
ThreadPool.SetMinThreads(3, minIOC);
for(int i = 0; i < 3; i++)
{
    ThreadPool.QueueUserWorkItem(new WaitCallback(callback), i.ToString());
}
// give the ThreadPool a change to run
Thread.Sleep(1000);

标准线程池的一个很好的替代方案是任务并行库,它引入了任务的概念。例如,使用 Task 对象,您可以轻松启动多个任务,如下所示:

// global variable
Random random = new Random(); // used to simulate different work time
// unit of work
private void callback(int i)
{
    Console.WriteLine(String.Format("Nr. {0}", i));
    System.Threading.Thread.Sleep(random.Next(100, 1000));
}   
const int max = 5;
var tasks = new System.Threading.Tasks.Task[max];
for (int i = 0; i < max; i++)
{
    var copy = i;
    // create the tasks and init the work units
    tasks[i] = new System.Threading.Tasks.Task(() => callback(copy));
}
// start the parallel execution
foreach (var task in tasks)
{
    task.Start();
}
// optionally wait for all tasks to finish
System.Threading.Tasks.Task.WaitAll(tasks);

您也可以使用 Task.Factory 立即启动代码执行,如下所示:

const int max = 5;
var tasks = new System.Threading.Tasks.Task[max];
for (int i = 0; i < max; i++)
{
    var copy = i;
    // start execution immediately
    tasks[i] = System.Threading.Tasks.Task.Factory.StartNew(() => callback(copy));
}
System.Threading.Tasks.Task.WaitAll(tasks);

看看这篇SO文章,看看ThreadPool.QueueUserWorkItem与Task.Factory.StartNew之间的区别。