c# - 关于 C# 委托(delegate)的一个问题

标签 c# multithreading delegates

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() 

打印“消息” 还有这个

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();

关于c# - 关于 C# 委托(delegate)的一个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6309706/

相关文章:

c# - WP7动态更新UI而不阻塞线程

swift - 从委托(delegate)方法修改 View Controller 属性

c# - 事件、委托(delegate)、回调、INotifyPropertyChanged

c# - 用于替换字符串的正则表达式模式

c# - 在 C# 中使用正则表达式删除 css 样式

python - 字典在多线程应用程序的迭代过程中更改了大小

c++ - 多线程减慢程序 : no False-sharing, 没有互斥锁,没有缓存未命中,工作量不小

linux - 内核编程 - 互斥量

ios - RevMobAds 委托(delegate)问题

c# - NHibernate - 非空属性引用空值或 transient 值