如何将嵌套线程与其父线程或调用线程同步 [英] how to synchronize nested thread with its parent or calling thread

查看:122
本文介绍了如何将嵌套线程与其父线程或调用线程同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





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.

推荐答案

不确定这个解决方案是否完美匹配,但现在确实如此。至少你应该知道同步。



密钥是类 AutoResetEvent WaitHandle



创建一个包含线程方法的类。

Not sure if this solution is a perfect match, but here it is. At least you should get an idea about synchronization.

The keys are the classes AutoResetEvent and WaitHandle.

Create a class that contains the thread method.
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);


这篇关于如何将嵌套线程与其父线程或调用线程同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆