Have you ever wondered about local variables of static methods? Are they static too? Or are they call-specific? What happens with the variables when a second thread calls the method while the first has not finished executing it yet? The code below allows examining this.
// You may need to run this C# .NET console application
// a few times before you get interesting results
// Have fun!
using System;
using System.Threading;
namespace Andraszek.net
{
class StaticMethodExample
{
public static void ShowXTwice ()
{
// Uncomment the line below to see what happens if only one thread at
// a time is allowed to use type StaticMethodExample
// Observe the average number of ticks go up
//lock (typeof(StaticMethodExample))
{
Random r = new Random();
// Although the ShowXTwice method is static, each thread has its own instance of x
// otherwise, all threads would use the same variable
// and as a result sometimes x would have a different value when checked for the
// second time.
// For example: x checked for the first time by thread 1 (x=123), then thread 2
// assigns a new value to x (x=456), and now thread 1 checks x for the second time
//
int x = r.Next(1, 10000);
Console.WriteLine(Thread.CurrentThread.Name
+ " Checking x for the first time: " + x.ToString());
Console.WriteLine(Thread.CurrentThread.Name
+ " Checking x for the second time: " + x.ToString());
}
}
}
class TestStaticMethodExample
{
public static void Main()
{
int maxThreads = 100;
Thread[] threads = new Thread[maxThreads];
for (int i = 0; i < maxThreads; i++)
{
Thread t = new Thread(
new ThreadStart(StaticMethodExample.ShowXTwice));
t.Name = "Thread " + i.ToString();
threads[i] = t;
}
long startTicks = DateTime.Now.Ticks;
for (int i = 0; i < maxThreads; i++)
{
threads[i].Start();
}
// wait for all threads to finish
for (int i = 0; i < maxThreads; i++)
{
threads[i].Join();
}
long endTicks = DateTime.Now.Ticks;
Console.Write("Number of ticks from start to end: ");
Console.WriteLine(endTicks - startTicks);
Console.WriteLine("Press Enter");
Console.ReadLine();
}
}
}
Here is the output:

No comments:
Post a Comment