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);
}
}
}
Why the following code
ClassB b = new ClassB();
b.test2()
prints “msg”
and this one
ClassB b = new ClassB();
b.test1()
doesn’t print anything?
Your program likely exits causing the thread to be terminated (or before the thread has time to start). Just as you explicitly created a thread, you need to explicitly wait for the thread to complete!
You need to use
Thread.Joinor some other method to keep the main program waiting for the thread to complete.One possible option, using
Thread.Join:Another option, using a
ManualResetEvent:Then your code which call
b.test2():