class ClassA { public delegate void WriteLog(string msg); private WriteLog m_WriteLogDelegate; public ClassA(WriteLog writelog) { m_WriteLogDelegate = writelog; Thread thread = new Thread(new ThreadStart(Search)); thread.Start(); } public void Search() { /* ... */ m_WriteLogDelegate("msg"); /* ... */ } } class classB { private ClassA m_classA; protected void WriteLogCallBack(string msg) { // prints msg /* ... */ } public classB() { m_classA = new ClassA(new WriteLog(WriteLogCallBack)); } public void test1() { Thread thread = new Thread(new ThreadStart(Run)); thread.Start(); } public void test2() { m_classA.Search(); } public void Run() { while(true) { /* ... */ m_classA.Search(); /* ... */ Thread.Sleep(1000); } } }
为什么以下代码
ClassB b = new ClassB(); b.test2()
打印“msg”
还有这个
ClassB b = new ClassB(); b.test1()
什么都不打印?
解决方法
您的程序可能会退出,导致线程被终止(或者在线程有时间启动之前).就像你明确创建一个线程一样,你需要显式等待线程完成!
您需要使用Thread.Join或其他一些方法来保持主程序等待线程完成.
一个可能的选择,使用Thread.Join:
public Thread test2() { ... return thread; } ... b.test2().Join(); // wait for test2 to complete
另一个选项,使用ManualResetEvent:
class classB { private ManualResetEvent mre = new ManualResetEvent(false); ... private void Run() { ... this.mre.Set(); // we completed our task } public void Wait(); { this.mre.WaitOne(); }
然后你的代码调用b.test2():
b.test2(); b.Wait();