Threading Join issue - getting Join_Timeout Exception.

Hi all,

I have an application that creates an object which creates a thread in its constructor. The application then starts this threads by calling the Start() property on this object, and then calls a Thread.Sleep(), and then the Stop property to stop the Thread() - and example of the code is below..with the issue I am getting provided below.

static void Main()
{
PowerNotifications pn = new PowerNotifications();
pn.Start();
Thread.Sleep(10000);
pn.Stop();
}

public class PowerNotifications
{
public PowerNotifications()
{
t = new Thread(new ThreadStart(DoWork));
}

public void Start()
{
t.Start();
}

public void Stop()
{
done = true;
t.Abort();
}

private void DoWork()
{
// Do some execution...
t.Join(20000);
}
}

Now my problem is this. Because the time passed into the Join method is greater (20000) than the Thread.Sleep(10000) I get a Join_Timeout exception. But if I remove the Thread.Sleep(10000) the application doesn't hold up for the time specified in the Join(20000) call. I deally, I don't want to specify a time in the Thread.Sleep() call (or even specify it at all) because I simply don't know how long the thread (t in this case) will be executing for.

How do I solve this

(if you feel I haven't explained myself well enough, please state so, and I will try to clarify things)

Thanks

Tryst



Answer this question

Threading Join issue - getting Join_Timeout Exception.

  • katarn85

    Hi Peter,

    I think I understand your answer.

    What I had initially was the t.Join() in a while loop, and not directly after the t.Start() call. I guess having it in the loop was causing the Exception.

    So just to clarify on this. calling Join() on a thread (t) will make the calling thread (the one that started the thread, (t)) wait for the thread (t) to finish executing before the calling thread can resume its work.

    Tryst


  • TimBW

    Hi,

    I did not understand your scenario very much, did you mean you will create a new thread, and the main thread will wait for the new thread to exit. It will wait for 20s.

    class PowerNotifications
    {
    static void Main()
    {
    Thread t = new Thread(new ThreadStart(ThreadProc));
    t.Start();
    t.Join();
    }
    static void ThreadProc()
    {
    for (int i = 10- 1; i >= 0; i--)
    {
    Thread.Sleep(1000);
    Console.WriteLine("Running");
    }
    }
    }

    If you still have any concern, please feel free to post here.

    Best regards,
    Peter Huang



  • MannyH

    Hi Tryst,

    You are right.
    t.Join() will cause the calling thread blocked till the Thread t finished.

    http://msdn2.microsoft.com/en-us/library/system.threading.thread.join(d=ide).aspx
    If you still have any concern, please feel free to post here.

    Best regards,
    Peter Huang



  • Threading Join issue - getting Join_Timeout Exception.