4

Nutshell: I launch a thread from my form, then some time later use the Join method on it. It terminates but my application is stuck on the Join and refuses to acknowledge that it's done joining. What would cause this to happen? My thread is launched from a button on my form, and attempts to join from a second button on the same form.

More Info: I have an application that uses threading to accomplish communications and number crunching. Assuming the Main Form to be the parent thread, the first child is Child1. Upon starting Child1 establishes some communications with external devices and launches 2 child threads of its own (Child2 and Child3) to process the incoming data.

When the user decides that the application is to stop processing incoming data I need Child1 to terminate (so com settings can be altered prior to resuming, if necessary). I set a stop event and Child1 exits its execution loop, the first things it does is notify Child2 and Child3 that they are no longer needed (via another stop event), Child2 and Child3 are waited for with the Join method within Child1. This works just fine.

What does not work is that the form also uses the Join method on Child1 after setting the stop event that prompted Child1 to exit it's run loop and terminate, this Join, however, waits indefinitely.

Stepping Through: When I step through my app I notice that at the moment before using Join the IsAlive property is true. After I hit Child1.Join() I can no longer get any information from the thread because it's in "JoinWaitSleep". However, if I run a while loop that causes the form thread to sleep while Child1.IsAlive is true, this works just fine. Is my second button somehow part of a thread that cannot join Child1 to it?


public void Run()
{   //Known as Child1
    //code to setup coms is here

    //Launch Builder threads
    InsertBackgroundMonitor("Launching Collector Threads");
    RunBuilders = true;

    //Known as Child2 and Child3
    BuildThread1 = new Thread(new ThreadStart(Cam1Builder));
    BuildThread2 = new Thread(new ThreadStart(Cam2Builder));
    BuildThread1.Start();
    BuildThread2.Start();

    while (!StopEventHandle.WaitOne(0, true))
    {
    //// Code that waits for coms and tosses data into lists
    }

    RunBuilders = false;

    //Wait for threads to terminate
    BuildThread1.Join();
    BuildThread2.Join();
}

private void RunButton_Click(object sender, System.EventArgs e)
{
    //Button for running the control thread
    ControlThread = new Thread(new ThreadStart(Run));
    ControlThread.Start();
}

private void StopButton_Click(object sender, System.EventArgs e)
{
    if (btnStop.Enabled)
    {   //Button for stopping the control thread
        StopEventHandle.Set();

        if (ControlThread != null)
        {
            while (ControlThread.IsAlive)
            {
                Thread.Sleep(100);
            }
            //somehow Join did not work
            //ControlThread.Join();
        }

        //Update buttons
        btnStart.Enabled = true;
        btnStop.Enabled = false;               
    }
}
10
  • 2
    Can we see a simple example of the code in action? Jun 21, 2011 at 14:38
  • I've added some example code. I cut out all the coms and did not include the actual contents of Child2 and Child3. They both end nicely though as I make it past both their joins without any worry. Their exit is caused by RunBuilders = false. Jun 21, 2011 at 14:58
  • 1
    Is RunBuilders volatile? Jun 21, 2011 at 15:58
  • No it is not. Should it be? RunBuilders is only changed by Child1 and only read by Child2 and Child3, but their Join methods both return normally. Jun 21, 2011 at 16:20
  • 1
    Ok, what does InsertBackgroundMonitor do? I'm not aware of this function, and a google search makes me think it's not any standard function.
    – DanTheMan
    Jun 21, 2011 at 19:05

3 Answers 3

2

It's difficult to say without more code, but you have SOME resource that you've started that you're not properly shutting down.

Join() waits for the thread to be completely shut down, and all resources released before returning. If the Thread has any BackgroundWorker tasks, or if it has any spare tasks that you aren't showing still running it will not return.

Since both of the BuildThread1 and BuildThread2 are returning correctly, and Join'ing, you can be sure it's not one of those, or anything that they're doing. Look over the rest of the code. What does it do?

EDIT: This works fine:

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }


    Thread ControlThread;
    Thread BuildThread1;
    Thread BuildThread2;
    volatile bool RunBuilders = true;
    volatile bool RunControl = true;

    private void button1_Click(object sender, EventArgs e)
    {
        ControlThread = new Thread(new ThreadStart(Run));
        ControlThread.Start();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        RunControl = false;

        if (ControlThread != null)
        {
            while (ControlThread.IsAlive)
            {
                Thread.Sleep(100);
            }
            //somehow Join did not work
            ControlThread.Join();
        }
    }

    public void Run()
    {   //Known as Child1
        //code to setup coms is here

        //Launch Builder threads
        RunBuilders = true;

        //Known as Child2 and Child3
        BuildThread1 = new Thread(new ThreadStart(Cam1Builder));
        BuildThread2 = new Thread(new ThreadStart(Cam1Builder));
        BuildThread1.Start();
        BuildThread2.Start();

        while (RunControl)
        {
        //// Code that waits for coms and tosses data into lists
        }

        RunBuilders = false;

        //Wait for threads to terminate
        BuildThread1.Join();
        BuildThread2.Join();
    }


    public void Cam1Builder()
    {
        while ( RunBuilders )
        {

        }
    }
}
}
7
  • If I put a break just before my Join method the IsAlive property becomes false. Unless I'm mistaken this means that the thread exits properly (and releases whatever resources it is supposed to) if I refrain from blocking the UI thread with the Join method. Jun 21, 2011 at 19:19
  • I see your edit, and yes waiting 100ms before the Join makes it work for me too, if I call Join before ControlThread terminates it will wait on Join indefinitely. If I call Join after ControlThread terminates it will just pass by the Join. I am not sure if 100ms will always be enough, and I don't want to wait an arbitrary amount of time. Brain is definitely on to something with the blocked message pump suggestion, but I don't know a better alternative. Jun 21, 2011 at 20:03
  • But.. I didn't add that. That's in your original code :-/ I wasn't adding that, and actually just spinning works too, so I'll go delete it to prove it still works. This has nothing to do with the message pump being blocked. There you would see your screen turn white and it would say 'application not responding'.
    – DanTheMan
    Jun 21, 2011 at 20:51
  • Yup removing that Sleep(100) still causes all threads to close down just fine. There's something else in your code still running.
    – DanTheMan
    Jun 21, 2011 at 20:52
  • Yes, that is in my original code. I had it in there to show what I was doing instead of a simple Join. For me, removing the Sleep(100) makes it pause forever on Join. So, if my Control thread exits naturally when I wait 100ms, the only reason it would pause forever on Join would be if the ControlThread needs the UI thread running in order to fully terminate. What do I do? Jun 21, 2011 at 20:59
1

I can only guess at the possible issues that would cause this since I do not see the code for the Cam1Builder and Cam2Builder methods.1 The possibilities that immediately jump out at me are:

  • Calling Join blocks execution of the calling thread. If this is done from a UI thread then it stops the message pump. If the worker is trying to post messages to the UI thread (via Control.Invoke for example) then both threads will deadlock.
  • If RunBuilders is not marked as volatile or accessed inside a lock then its value, as perceived by other threads, cannot be predicted at any given point in time.

In general it is not advisable to call Join from the UI thread. UI threads are special in that they are running an indefinite loop which is dispatching and processing windows messages. This loop is initiated by calling Application.Run which you should see somewhere in your code. If you block the UI thread by calling Join or other blocking method then it cannot process queued messages. It is possible that you are using Control.Invoke to marshal the execution of a delegate on the UI thread from one of the worker threads. If this is the case then both threads will deadlock. Join blocks the UI thread waiting for the worker thread. Control.Invoke blocks the worker thread waiting for the UI thread.

Variables used as communication mechanisms between threads should be made thread-safe. In your case you are using RunBuilders as a mechanism for signaling an action on a worker thread. The problem is that since RunBuilders is neither marked as volatile nor accessed from within a lock block then its value cannot be reliably transferred to the worker thread. You may be setting its value to true in one thread, but another thread could continue to read false indefinitely.


1If you post more code I might be able to provide better insight. Specifically, I would like to see the general outline of what Cam1Builder or Cam2Builder is doing especially the parts where it is reading RunBuilders.

4
  • My Cam1Builder and Cam2Builder threads are almost doing identical tasks, the difference being that they monitor two different input buffers. Their only use of RunBuilders is their encompassing loops, it's just declarations while(RunBuilders){check and process buffers}. I've upgraded the RunBuilders variable to volatile. So, since it is not advisable to Join threads with the UI thread, is my "while(ControlThread.IsAlive)" solution reasonable? Jun 21, 2011 at 18:53
  • No, while(ControlThread.IsAlive) is not reasonable. This ALSO holds up the UI thread, same as Join().
    – DanTheMan
    Jun 21, 2011 at 19:01
  • What is the best way to "join" my ControlThread? The while loop, although it holds up the UI thread, it still allows it to process. I think your answer is the most correct because it is the only one that explains why the while loop exits eventually and the Join method halts indefinitely. Jun 21, 2011 at 19:16
  • Also, the ControlThread does post messages to the UI, of course, I may be mistaken as to what this means... I am invoking a delegate function from ControlThread to the UI to update the screen based on processed data. The case that I'm looking at is one where we have not used that delegate function at all. Jun 21, 2011 at 19:57
1

Did you try changing RunBuilders to volatile? Personally I don't know as I'd use a bool in this manner cross-threads, but if you're going to it should be volatile so all threads see the update instead of a stale value "cached" away by the JIT.

Other than that would need to see what the two other threads are doing.

1
  • I did make RunBuilders volatile. Those other two threads exit properly, I know because if I step through the ControlThread I can watch it step past both the Join methods without any incident. I can also step the ControlThread off the final "}", this doesn't budge the ControlThread.Join method. Jun 21, 2011 at 19:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.