Sometimes a thread does not start

I ran into some kind of problem, I can’t understand why this is happening. Here is a simple example:

class ConsoleApp { static void Main(string[] args) { Thread workThread = new Thread(ThreadProc); //Console.WriteLine("Starting"); // uncomment this workThread.Start(); Console.ReadKey(true); // first ReadKey Console.ReadKey(true); // second ReadKey } static void ThreadProc() { Console.WriteLine("ThreadProc started"); Random rnd = new Random(); for (int i = 0; i < 5; i++) { int timeout = rnd.Next(500, 1000); Thread.Sleep(timeout); Console.WriteLine("ThreadProc {0} slept {1} ms", i, timeout); } } } 

When I run this, workThread does not start until I press a key (after the first ReadKey). If I uncomment the first Console.WriteLine, workThread will start immediately.

Can anyone explain this behavior?

+4
source share
2 answers

This is an ideal case of race condition . Here you create a stream and then start it. But keep in mind there is a delay for the actual start of the thread when you call the start method on it. This delay is likely to give your Console.ReadKey method a chance to enter the execution thread and wait for user input. At this point, the Console.ReadKey method locks your console with a lock on Console.InternalSyncObject and blocks waiting for input. In this case, the other execution path is blocked until we enter it. As soon as you press the key, which indirectly releases the lock on Console.InternalSyncObject and allows the thread to continue execution. I suppose this is what happens in your case.

Although this does not mean that you are trying to achieve, you can see the flow executing when replacing Console.RedKey with Console.ReadLine() .

+4
source

The static Console class is thread safe, there is a lock inside. Sometimes a ReadKey call blocks before calls inside your ThreadProc . This is called a race condition.

0
source

Source: https://habr.com/ru/post/1479482/


All Articles