活动后线程未完成

问题描述 投票:2回答:1

看看这个简单的类:

delegate void Log(String message);
class A {
  public Log log;

  ...

  public void test() {
    // Empty
  }

}

现在我从主GUI线程创建并启动一个线程,并检查它是否结束。

A a = new A();
a.log += Log;

Thread t = new Thread(new ThreadStart(a.test));
t.Start();

while(true) {
  System.Threading.Thread.Sleep(200);
  Console.WriteLine(t.IsAlive);

}

使用上面的代码一切正常:

true
true
....
false
false
false
...

现在,当我将test方法的代码更改为

public void test() {
  log("Test");
}

GUI类中的Log方法如下所示:

private void Log(String message)
        {
            if (this.tb_log.InvokeRequired)
            {
                this.tb_log.Invoke((MethodInvoker)delegate()
                {
                    Log(message);
                });
            }
            else
            {
                // do something with the textbox in the GUI
            }
        }

现在,虽然函数终止,但我得到以下控制台日志:

true
true
true
true
true
true
...

线程永远不会终止。你能解释一下吗?

c# multithreading events terminate
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.