[英]Thread handling in c#
I have the following code.. When i am executing this code, all the 5 thread windows are displaying at the same time. 我有以下代码。当我执行此代码时,所有5个线程窗口都同时显示。 But I want to execute a single thread with some value in each iteration. 但是我想在每次迭代中执行一个具有某些值的单个线程。 More than two threads should not be executed at a time.. The second thread(key=1) should start only after the completion of the first thread(key=0), and third thread(key=2) only after the completion of the second thread, and so on. 不应一次执行两个以上的线程。第二个线程(key = 1)仅应在第一个线程(key = 0)完成后启动,而第三个线程(key = 2)仅应在第一个线程完成后启动。第二个线程,依此类推。 Please help.. How can deal with this problem. 请帮助。.如何解决这个问题。
for (long key = 0; key < 5; key++)
{
var processingThread = new Thread(() => DoDataSetup(key));
_progress = new ProgressReport(processingThread);
_progress.Show();
_progress.FormClosed += delegate(object delSender, FormClosedEventArgs args)
{
this.Enabled = true;
};
this.Enable d = false;
processingThread.Start();
}
First of all it is better to use ThreadPool for Task creation, but I suggest you to create threads with use of Task.Run(...) . 首先,最好使用ThreadPool进行Task创建,但是我建议您使用Task.Run(...)创建线程。 For allowing to enter only a limited number of threads you could use the Semaphore class, or you use the BatchBlock of the TPL-API 为了只允许输入有限数量的线程,可以使用Semaphore类,也可以使用TPL-API的BatchBlock
//with semaphore
var semaphore = new Semaphore(0,2);
for(long key = 0; key < 5; key++)
{
semaphore.WaitOne();
ProcessWorking(key);
semaphore.Release();
}
public void ProcessWorking(long key)
{
var processingThread = new Thread(() => DoDataSetup(key));
_progress = new ProgressReport(processingThread);
_progress.Show();
_progress.FormClosed += delegate(object delSender, FormClosedEventArgs args)
{
this.Enabled = true;
};
this.Enabled = false;
processingThread.Start();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.