In order to check how variables (in my example "connection") are referred/shared by different threads, I wrote the following code and I found that each thread got its own connection (executing DoAnotherTask method).
I want to understand how this is handled by runtime, does each thread creates its own copy of variable and point to appropriate object, when a thread comes in CreateSharedConnection static method?
public static void StartThreadTest()
{
System.Threading.Thread thread1 = new System.Threading.Thread(new System.Threading.ThreadStart(CreateSharedConnection));
thread1.Name = "Thread 1";
thread1.Start();
System.Threading.Thread.Sleep(1000);
//Second Thread Going before First is completed with connection.
System.Threading.Thread thread2 = new System.Threading.Thread(new System.Threading.ThreadStart(CreateSharedConnection));
thread2.Name = "Thread 2";
thread2.Start();
System.Threading.Thread.Sleep(1000);
//Third Thread Going before Second is completed with connection.
System.Threading.Thread thread3 = new System.Threading.Thread(new System.Threading.ThreadStart(CreateSharedConnection));
thread3.Name = "Thread 3";
thread3.Start();
System.Threading.Thread.Sleep(1000);
//Fourth Thread Going before Third is completed with connection.
System.Threading.Thread thread4 = new System.Threading.Thread(new System.Threading.ThreadStart(CreateSharedConnection));
thread4.Name = "Thread 4";
thread4.Start();
}
/// <summary>
/// This is to start multiple threads.
/// </summary>
public static void CreateSharedConnection()
{
ThreadingPractice.GenericConnection connection= new ThreadingPractice.GenericConnection();
connection.DoTaskWithSleep();
//First Thread should invoke it again once second Thread has created a new connection after 1 Second.
connection.DoAnotherTask();
}
Generic Connection Class:
public class GenericConnection
{
public long ObjectIdentifier = 0;
public GenericConnection()
{
ObjectIdentifier = System.DateTime.Now.Ticks;
Console.WriteLine("Thread: " + System.Threading.Thread.CurrentThread.Name + "Generic Connection has been created at: " + DateTime.Now.ToString() + " with Unique Identifier of " + ObjectIdentifier.ToString());
}
/// <summary>
/// This method is kept to make a call stuck for few seconds as if doing a IO intensive Query.
/// </summary>
public void DoTaskWithSleep()
{
System.Threading.Thread.Sleep(2000);
Console.WriteLine("Thread: " + System.Threading.Thread.CurrentThread.Name + " Sleep has been done at: "+ System.DateTime.Now.ToString() + " This object has identifier as ##" + ObjectIdentifier.ToString());
}
public void DoAnotherTask()
{
System.Threading.Thread.Sleep(1000);
Console.WriteLine("Thread: " + System.Threading.Thread.CurrentThread.Name + "Done another task at: " + System.DateTime.Now.ToString() + " This object has identifier as ##" + ObjectIdentifier.ToString());
}
}