[Mono-list] Threading

Ian McCullough ipmccmono@hotmail.com
Mon, 13 May 2002 09:41:37 -0400


> Message: 20
> Date: Sun, 12 May 2002 22:45:04 +0100
> From: Dick Porter <dick@ximian.com>
> To: mono-list@ximian.com
> Subject: Re: [Mono-list] Threading
>
> On Sun, May 12, 2002 at 01:09:17PM +0100, Jonathan Stowe wrote:
> > Before I bugzilla this is there anything fundamentally wrong with :
> >
> [...]
> >
> > I am expecting it to run DoThread() ...
>
> It will if you run it enough times...
>
> Basically, sometimes Main() exits before DoThread() gets going.  It should
> be waiting for the thread that was started.
>
> Please bugzilla this.

Hold up a sec! If I'm correct, this behavior is "By Design."  If you want
the main thread of execution to wait for the other one, you must tell it to.
The simplest way to do this would be to modify TestThread() to be like this:

public TestThread()
{
    Console.WriteLine("In Constructor");
    try
    {

        Thread th = new Thread(new ThreadStart(DoThread));
        th.Start();
        th.Join();
    }
    catch(Exception e)
    {
        Console.WriteLine("Listening :" + e.ToString());
    }
}

Note the call to Thread.Join()  This tells the main thread (where the call
to Join gets executed) to cease execution and wait for th to exit.  Another
option you'll run across is to use a ManualResetEvent.  Like so:

class TestThread
{
    private static ManualResetEvent myMRE = new ManualResetEvent(false);

    public TestThread()
    {
        Console.WriteLine("In Constructor");
        try
        {

            Thread th = new Thread(new ThreadStart(DoThread));
            th.Start();
        }
        catch(Exception e)
        {
            Console.WriteLine("Listening :" + e.ToString());
        }
    }

    private void DoThread()
    {
        Console.WriteLine("In DoThread");
        myMRE.Set();
    }

    public static void Main()
    {

        TestThread theThread = new TestThread();
        myMRE.WaitOne();
    }
}

Please note, what appears above is meant to illustrate ManualResetEvent in
the most trivial way possible, it is not good coding style and its not to be
treated as such.  You can also use any number of other synchronization
primitives, but essentially, unless the main thread is explicitly waiting
for the other thread, there is a chance that the death of the main thread
immediately upon return from the TestThread() call will cause the death of
the thread before it gets a chance to send stuff to the console.  When the
main thread of execution dies it takes all the others with it, forcibly.

Ian