问题描述
i我调用2个或更多线程取决于具体情况,所以如何同步这些线程。
i意思是说,当这两个线程完成时,控件应该返回到调用线程,否则它应该等待。
i我使用一个简单的窗口形式,它包含一个按钮,在这个按钮的click事件上,我启动一个线程,它调用另一个方法,并在该方法中我已经声明了超过2个线程(根据条件)。
第一个线程完成而第二个线程正在运行时出现问题,并且调用线程在参数中发送一个新值。
i希望调用线程应该等到所有这些线程都被刷新。
请给我任何建议。
i am calling 2 or more threads depends on the situation, so how to synchronize these threads.
i mean to say, that when both of these threads finishes then the control should return to the calling thread otherwise it should wait.
i am using a simple window form, it contains a a button, on the click event of this button, i start a thread, it calls another method and in that method i have declared more than 2 thread (based on the condition).
problem occurs when first thread finishes while the second is running , and the calling thread sends a new value in the parameter.
i want that the calling thread should wait until all these thread finshed.
any suggestion please.
推荐答案
public class WorkingClassHero
{
public AutoResetEvent I_am_done;
public WorkingClassHero()
{
I_am_done = new AutoResetEvent(false);
}
public void DoWork()
{
AddCodeToDoTheJob();
I_am_done.Set();
}
}
然后启动线程并等待它们完成。
Then start the threads and wait for the them to finish.
WorkingClassHero hero1 = new WorkingClassHero();
Thread t1 = new Thread(new ThreadStart(hero1.DoWork));
WorkingClassHero hero2 = new WorkingClassHero();
Thread t2 = new Thread(new ThreadStart(hero2.DoWork));
WaitHandle[] waitHandles = new WaitHandle[]
{
hero1.I_am_done,
hero2.I_am_done
};
t1.Start();
t2.Start();
WaitHandle.WaitAll(waitHandles);
这篇关于如何将嵌套线程与其父线程或调用线程同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!