Lock
没有按预期工作,这是代码。我在这里应用线程,但我会将它应用到ASP.NET应用程序。
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;
}
}
它给了我以下输出
0
0
0
3
4
4
6
7
8
9
我期待着
0
1
2
3
4
5
6
7
8
9
我在哪里做错了?
我应该readonly object
按照这里的描述 使用C# lock(mylocker) not work