Lock
is not working as expected, here is the code.
I am applying thread here, but I will apply it to ASP.NET application.
class Program
{
static void Main(string[] args)
{
ThreadManager.CurrentSession = 0;
for (int i = 0; i < 10; i++)
{
CreateWork objCreateWork = new CreateWork();
ThreadStart start = new ThreadStart(objCreateWork.ProcessQuickPLan);
new Thread(start).Start();
}
Console.ReadLine();
}
}
class CreateWork
{
private object CurrentSession = -1;
public void ProcessQuickPLan()
{
lock (CurrentSession)
{
CurrentSession = ThreadManager.CurrentSession;
Console.WriteLine(CurrentSession);
ThreadManager.CurrentSession = Convert.ToInt32(ThreadManager.CurrentSession) + 1;
}
}
}
class ThreadManager
{
public static object CurrentSession
{
get;
set;
}
}
It is giving me following output
0
0
0
3
4
4
6
7
8
9
And I am expecting
0
1
2
3
4
5
6
7
8
9
Where am I doing wrong?
Should I use readonly object
as described here C# lock(mylocker) not work