So, i'm studying the .NET Thread class based on the book: Exam Ref 70-483: Programming in C#, and i noticed something i don't know why it happens or if it should be happening.
The book give me this part of code on page 4:
public static class Program
{
public static void ThreadMethod()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("ThreadProc: {0}", i);
Thread.Sleep(0);
}
}
public static void Main()
{
Thread t = new Thread(new ThreadStart(ThreadMethod));
t.Start();
for (int i = 0; i < 4; i++)
{
Console.WriteLine("Main thread: Do some work.");
Thread.Sleep(0);
}
t.Join();
}
}
With the expected result showing below, since at each Thread.Sleep(0), the current thread exits and go to work on the next thread on the queue:
// Main thread: Do some work.
// ThreadProc: 0
// Main thread: Do some work.
// ThreadProc: 1
// Main thread: Do some work.
// ThreadProc: 2
// Main thread: Do some work.
// ThreadProc: 3
// ThreadProc: 4
// ThreadProc: 5
// ThreadProc: 6
// ThreadProc: 7
// ThreadProc: 8
// ThreadProc: 9
But when i built my version of this, it didn't work as expected, even when i copy pasted the code and ran on my machine, it give this result every time a executed the program, with the same code above:
// Main thread: Do some work.
// ThreadProc: 0
// ThreadProc: 1
// ThreadProc: 2
// ThreadProc: 3
// ThreadProc: 4
// ThreadProc: 5
// ThreadProc: 6
// ThreadProc: 7
// ThreadProc: 8
// ThreadProc: 9
// Main thread: Do some work.
// Main thread: Do some work.
// Main thread: Do some work.
As you can see, it seems to enter the side thread and when i call Thread.Sleep(0) method it don't go back to the main thread as it should, and keeps working on the side thread until it finishes.
As an workaround for this, i used the Random class to generate a random number between 100 and 500 to pass to the Thread.Sleep() method, and it starts to work as expected:
public static class Program
{
public static void ThreadMethod()
{
var rand = new Random();
for (int i = 0; i < 10; i++)
{
Console.WriteLine("ThreadProc: {0}", i);
Thread.Sleep(rand.Next(100, 500));
}
}
public static void Main()
{
Thread t = new Thread(new ThreadStart(ThreadMethod));
t.Start();
var rand = new Random();
for (int i = 0; i < 4; i++)
{
Console.WriteLine("Main thread: Do some work.");
Thread.Sleep(rand.Next(100, 500));
}
t.Join();
}
}
With the results looking like this:
// Main thread: Do some work.
// ThreadProc: 0
// ThreadProc: 1
// ThreadProc: 2
// Main thread: Do some work.
// ThreadProc: 3
// Main thread: Do some work.
// ThreadProc: 4
// Main thread: Do some work.
// ThreadProc: 5
// ThreadProc: 6
// ThreadProc: 7
// ThreadProc: 8
// ThreadProc: 9
I don't think the book was written on the .NET Core framework, and i thought this "problem" may be caused by the changes on the synchronization context between these two frameworks. I checked the priority of the two threads and is set as the default "Normal".
Anyone have an idea of why this happens?