如果你有一个主线程启动另外两个线程.使主线程等待另外两个线程的最简洁方法是什么?
我可以使用bgndworker和sleep spinner来检查bgnd worker的IsBusy,但我认为有更好的方法.
编辑 更多要求:
主线程还有其他一些工作要做(例如GUI).
两个衍生线程应该能够报告异常并返回结果值
REA_ANDREW.. 10
使用Thread.Join()的快速示例;
Thread t1 = new Thread(new ThreadStart(delegate() { System.Threading.Thread.Sleep(2000); })); Thread t2 = new Thread(new ThreadStart(delegate() { System.Threading.Thread.Sleep(4000); })); t1.Start(); t2.Start(); t1.Join(); t2.Join();
使用等待句柄编辑另外3个示例:
ManualResetEvent[] waitHandles = new ManualResetEvent[]{ new ManualResetEvent(false), new ManualResetEvent(false) }; Thread t1 = new Thread(new ParameterizedThreadStart(delegate(object state) { ManualResetEvent handle = (ManualResetEvent)state; System.Threading.Thread.Sleep(2000); handle.Set(); })); Thread t2 = new Thread(new ParameterizedThreadStart(delegate(object state) { ManualResetEvent handle = (ManualResetEvent)state; System.Threading.Thread.Sleep(4000); handle.Set(); })); t1.Start(waitHandles[0]); t2.Start(waitHandles[1]); WaitHandle.WaitAll(waitHandles); Console.WriteLine("Finished");
Marc Gravell.. 5
请参阅此主题的答案.我喜欢这个选项 ;-p
Forker p = new Forker(); p.Fork(delegate { DoSomeWork(); }); p.Fork(delegate { DoSomeOtherWork(); }); p.Join();
重新返回值/报告异常 - 只需让每个分支在逻辑结束时作为回调...(您可以使用捕获的变量将状态传递到两个分支,包括共享记录器等).
使用Thread.Join()的快速示例;
Thread t1 = new Thread(new ThreadStart(delegate() { System.Threading.Thread.Sleep(2000); })); Thread t2 = new Thread(new ThreadStart(delegate() { System.Threading.Thread.Sleep(4000); })); t1.Start(); t2.Start(); t1.Join(); t2.Join();
使用等待句柄编辑另外3个示例:
ManualResetEvent[] waitHandles = new ManualResetEvent[]{ new ManualResetEvent(false), new ManualResetEvent(false) }; Thread t1 = new Thread(new ParameterizedThreadStart(delegate(object state) { ManualResetEvent handle = (ManualResetEvent)state; System.Threading.Thread.Sleep(2000); handle.Set(); })); Thread t2 = new Thread(new ParameterizedThreadStart(delegate(object state) { ManualResetEvent handle = (ManualResetEvent)state; System.Threading.Thread.Sleep(4000); handle.Set(); })); t1.Start(waitHandles[0]); t2.Start(waitHandles[1]); WaitHandle.WaitAll(waitHandles); Console.WriteLine("Finished");
请参阅此主题的答案.我喜欢这个选项 ;-p
Forker p = new Forker(); p.Fork(delegate { DoSomeWork(); }); p.Fork(delegate { DoSomeOtherWork(); }); p.Join();
重新返回值/报告异常 - 只需让每个分支在逻辑结束时作为回调...(您可以使用捕获的变量将状态传递到两个分支,包括共享记录器等).