C#线程 - 锁对象 [英] C# threading - Lock Object
问题描述
我试图锁定在C#应用了盒装的对象,这是不可能?
I am trying to lock a "boxed" object in a c# app, is this not possible?
class t
{
System.Object t_x = new object();
public t(int p)
{
t_x = p;
}
public void w()
{
lock (t_x)
{
for (int i = 0; i < 4; i++)
{
{
t_x = ((int)t_x) + 1;
Console.WriteLine(t_x);
Thread.Sleep(1000);
}
}
}
}
}
在其它类我就可以开始2个线程:
In another class I can start 2 threads:
Thread b1 = new Thread(new ThreadStart(t1.w));
b1.Start();
Thread b2 = new Thread(new ThreadStart(t1.w));
b2.Start();
然而该部分未锁定。
当我锁定的任意对象(即,一个创造,而不是修改为对象=新的对象()),它锁定良好。
是装箱操作有点depromotes我的对象??
However the portion is not locked. When I lock an arbitrary object (i.e. one created and not modified as object a=new object()) it locks well. Is boxing operation somehow "depromotes" my Object??
推荐答案
您需要创建一个单独的锁对象。问题是,你重新分配t_x内循环。假设线程B1循环中获得前B2获取到lock语句,B2将锁语句中被允许的,因为,到那时,t_x将是不会对一个锁的新对象。
You need to create a separate lock object. The problem is that you re-assign t_x inside the loop. Assuming thread b1 gets inside the loop before b2 gets to the lock statement, b2 will be allowed inside the lock statement because, by that time, t_x will be a new object that does not have a lock on it.
这篇关于C#线程 - 锁对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!