Michael
Michael

Reputation: 538

Thread not finishing after Event

Look at this simple class:

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

  ...

  public void test() {
    // Empty
  }

}

Now I am creating and starting a thread from the main GUI thread and check if it ends.

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

}

With that code above everything works fine:

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

Now when I change the code of the test method to

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

the Log method in the GUI-class looks like this:

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
            }
        }

Now, although the function terminates I am getting the following console log:

true
true
true
true
true
true
...

The thread never terminates. Can you explain this?

Upvotes: 2

Views: 90

Answers (1)

JMarsch
JMarsch

Reputation: 21753

Assuming that your while loop is happening on the GUI thread, you are never giving up control of the window (because you are in a loop). You should also find that your Invoke never returns. (it's asking the main thread to do something by placing a message in your window's message queue, but you have the main thread busy, so it never dequeues the message)

If this is just test code, you could use BeingInvoke instead, but really, you shouldn't be sleeping and checking active on the background thread from your UI thread.

Instead, have the background thread notify your window when it has completed by calling a delegate, or (much better) either use a BackgroundWorker (Winforms) or a Task, with a .ContinueWith() call to notify your window when it has completed.

Upvotes: 2

Related Questions