为什么我们不能锁定一个值类型? [英] Why can't we lock on a value type?
问题描述
我试图锁定
A 布尔
变量时,我遇到了以下错误:
I was trying to lock
a Boolean
variable when I encountered the following error :
布尔不是所要求的锁语句
'bool' is not a reference type as required by the lock statement
看来只有引用类型在锁允许
语句,但我不知道我明白为什么。
It seems that only reference types are allowed in lock
statements, but I'm not sure I understand why.
安德烈亚斯是说明在他的评论:
Andreas is stating in his comment:
在[值类型]对象从一个线程传递到另一个,它复制了一份,所以线程最终在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.
是真的吗?这是否意味着,当我这样做,我其实修改两个不同的 X
在 xToTrue
和 xToFalse
方法?
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:我知道有关的How~~V正确锁定值类型。我的问题是不相关的如何的,但到的为什么的
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...
但如果编译器让你锁定一个值类型,你最终会锁定什么都没有......因为每个时间传递你的价值类型为锁定
,你会路过它的盒装拷贝;不同的盒装拷贝。这样的锁会仿佛它们是完全不同的对象。 (因为,它们实际上是)
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)
请记住,当你传递一个值类型为类型对象
的参数,它得到盒装(包装)成引用类型。这使得每次发生这种情况时它一个全新的对象。
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屋!