I wrote a simple multi-threading snippet just to get myself used to this concept.
public void testThread(int arg1, ConsoleColor color)
{
for (int i = 0; i < 1000; i++)
{
Console.ForegroundColor = color;
Console.WriteLine("Thread " + color.ToString() + " : " + i);
Console.ResetColor();
Thread.Sleep(arg1);
}
}
Thread t1 = new Thread(() => program.testThread(1000, ConsoleColor.Blue));
Thread t2 = new Thread(() => program.testThread(1000, ConsoleColor.Red));
t1.Start();
t2.Start();
t1.Join();
t2.Join();
What I saw in my output console window is

I just don’t understand why sometimes the thread decorated with Red color could change itself to white or light gray color (whatsoever). Could you please help enlighten this mind?
Thanks in advance.
Your code block is not atomic. This means that the two threads can intertwine. Example:
If you want the threads’ actions to be atomic, i.e. uninterruptable, you need to use locking:
The lock statement ensures that only one of the threads in in the critical section at any given time: