BVernon
BVernon

Reputation: 3747

Why does this thread cause my application to hang up after multiple executions?

I created this test program to try to understand threading a little better:

namespace ThreadTest
{
    public class Class1
    {
        static Number number = new Number();

        static public void Go()
        {
            Thread t1 = new Thread(new ThreadStart(IncrementNumber));
            t1.Start();
            IncrementNumber();
        }

        public static void IncrementNumber()
        {
            number.Inc();
        }
    }

    public class Number
    {
        int x = 0;

        public void Inc()
        {

                x++;
                Debug.Write(x);
                Debug.Write(Environment.NewLine);
        }

        public override string ToString()
        {
            return x.ToString();
        }
    }
}

I am just executing it from the Immediate Window by calling ThreadTest.Class1.Go(). I noticed that from one execution to the next, as long as it doesn't have to recompile, the static members remain in memory and it continues to reuse them.

Here's what the immediate window looks like after four successive executions:

ThreadTest.Class1.Go()
2
1
Expression has been evaluated and has no value
ThreadTest.Class1.Go()
3
4Expression has been evaluated and has no value
ThreadTest.Class1.Go()
ThreadTest.Class1.Go()
An expression evaluation is already in progress.

The first execution looks as I would expect.

The second execution didn't manage to write the final Environment.NewLine. Is this possibly because execution from the main thread finished before execution on the t1 so that t1 had time to write the number, but not the new line? That seems unlikely but it's the only explanation I can come up with right now.

The third execution just hangs, which is evidenced by the output of the fourth attempt to execute it. Why would it hang?

Upvotes: 0

Views: 163

Answers (1)

Eric J.
Eric J.

Reputation: 150108

Indeed, execution of the main thread could have halted at that point.

A good indication that this is happening is if you get different output on different runs.

You will need to describe "hangs" a bit better to fully answer that aspect. If there was simply no output, that would indicate the main thread finished before any output from t1. If there is just no output but the program does not end, try breaking execution and looking at which line each thread is on for clues.

Try to Join t1 in your main thread to prevent the program from exiting before you are ready for it to.

Upvotes: 2

Related Questions