I'm a newbie to multi-threading in C#. I have created the following program:
class Program
{
static void Main(string[] args)
{
Thread.CurrentThread.Name = "main";
Thread t = new Thread(PrintName);
t.Name = "worker";
t.Start();
PrintName();
Console.ReadKey();
}
static void PrintName()
{
Console.WriteLine("Hello from " + Thread.CurrentThread.Name);
}
}
The output is
Hello from main
Hello from worker
If I change the body of PrintName()
method to
static void PrintName()
{
if (Thread.CurrentThread.Name == "main")
{
Thread.Sleep(x);
}
Console.WriteLine("Hello from " + Thread.CurrentThread.Name);
}
where x
>= 2, then the messages are output in reverse order
Why is that so? My reasoning is that in the first case, even though t.Start()
precedes PrintName()
in the Main()
method, not enough time passes by for the thread scheduler to switch execution between main
and worker
threads, and hence the output. Can someone clarify/negate my assumptions?