为什么我们不能锁定值类型? [英] Why can't we lock on a value type?
问题描述
当我遇到以下错误时,我试图lock
一个Boolean
变量:
I was trying to lock
a Boolean
variable when I encountered the following error :
'bool' 不是 lock 语句要求的引用类型
'bool' is not a reference type as required by the lock statement
似乎在 lock
语句中只允许引用类型,但我不确定我明白为什么.
It seems that only reference types are allowed in lock
statements, but I'm not sure I understand why.
Andreas 在他的评论中说:
Andreas is stating in his comment:
当 [a value type] 对象从一个线程传递到另一个线程时,会生成一个副本,因此线程最终会处理 2 个不同的对象,这是安全的.
When [a value type] object is passed from one thread to the other, a copy is made, so the threads end up working on 2 different objects, which is safe.
是真的吗?这是否意味着当我执行以下操作时,我实际上是在修改 xToTrue
和 xToFalse
方法中的两个不同的 x
?
Is it true? Does that mean that when I do the following, I am in fact modifying two different x
in the xToTrue
and the xToFalse
method?
public static class Program {
public static Boolean x = false;
[STAThread]
static void Main(string[] args) {
var t = new Thread(() => xToTrue());
t.Start();
// ...
xToFalse();
}
private static void xToTrue() {
Program.x = true;
}
private static void xToFalse() {
Program.x = false;
}
}
(仅此代码在其状态下显然没有用,仅用于示例)
(this code alone is clearly useless in its state, it is only for the example)
PS:我知道关于如何正确锁定值类型的这个问题.我的问题与如何无关,而是与为什么有关.
P.S: I know about this question on How to properly lock a value type. My question is not related to the how but to the why.
推荐答案
这里只是一个疯狂的猜测...
Just a wild guess here...
但是如果编译器让你锁定一个值类型,你最终什么也不会锁定......因为每次你将值类型传递给 lock
时,你都会传递一个盒装副本;不同的盒装副本.所以锁就好像它们是完全不同的对象.(因为,它们实际上是)
but if the compiler let you lock on a value type, you would end up locking nothing at all... because each time you passed the value type to the lock
, you would be passing a boxed copy of it; a different boxed copy. So the locks would be as if they were entirely different objects. (since, they actually are)
请记住,当您为 object
类型的参数传递值类型时,它会被装箱(包装)为引用类型.这使得每次发生这种情况时它都是一个全新的对象.
Remember that when you pass a value type for a parameter of type object
, it gets boxed (wrapped) into a reference type. This makes it a brand-new object each time this happens.
这篇关于为什么我们不能锁定值类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!