multithreading (unexpected?) behavior

Hi,

I'm using the following query below. I expect the code to print:

"
start
done
end
"

This happens every time I change the code and compile/run it for the first time. But from the second time the code is run without any changes the second line "done" is not printed. It seems that the secondary thread is entering the locked code first but that Console.WriteLine output is not shown.

I was wondering if this is expected behavior and I'm missing something?

Thanks,
void Main()
{
	ThreadTest.Main();
}

// Define other methods and classes here
class ThreadTest
{
	static bool _done = false;
	static readonly object _locker = new object();
	
	public static void Main()
	{
		Console.WriteLine("start");
		Thread t = new Thread(Go);
		t.Start();
		Go();
		t.Join();
		Console.WriteLine("end");
	}
	
	static void Go()
	{
		lock (_locker)
		{
			if (!_done)
			{
				Console.WriteLine("Done");
				_done = true;
			}
		}
	}
}

Comments

  • You need to set done false in your main method.

    Unless you have changed your query (and it needs to be recompiled) or have the 'Always use Fresh Process per execution' option in preferences enabled, then your static _done is only initialised on the first run.
  • Thank you. With a new process started every execution everything behaves as I was expecting.
  • Add this line after your Main method and everything is fine:
    Process.GetCurrentProcess().Kill();
  • Or alternatively, add the following code anywhere in your script:

    Util.NewProcess = true;
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!