问题描述
我的一个班级有一个Guid类型的属性.多个线程可以同时读取和写入此属性.我的印象是对Guid的读写不是原子的,因此我应该锁定它们.
One of my classes has a property of type Guid. This property can read and written simultaneously by more than one thread. I'm under the impression that reads and writes to a Guid are NOT atomic, therefore I should lock them.
我选择这样做:
public Guid TestKey
{
get
{
lock (_testKeyLock)
{
return _testKey;
}
}
set
{
lock (_testKeyLock)
{
_testKey = value;
}
}
}
(在我的课程中,对Guid的所有访问也都通过该属性完成,而不是直接访问_testKey.)
(Inside my class, all access to the Guid is also done through that property rather than accessing _testKey directly.)
我有两个问题:
(1)真的有必要像这样锁定Guid以防止读取被撕裂吗? (我很确定是这样.)
(1) Is it really necessary to lock the Guid like that to prevent torn reads? (I'm pretty sure it is.)
(2)这是进行锁定的合理方法吗?还是我需要像下面这样:
(2) Is that a reasonable way to do the locking? Or do I need to do it like the following:
get
{
Guid result;
lock (_testKeyLock)
{
result = _testKey;
}
return result;
}
本文确实确认了Guids会遭受读取撕裂的影响: http ://msdn.microsoft.com/zh-CN/magazine/jj863136.aspx
This article does confirm that Guids will suffer from torn reads: http://msdn.microsoft.com/en-us/magazine/jj863136.aspx
推荐答案
1)真的有必要像这样锁定Guid以防止读取中断吗? (我很确定是这样.)
1) Is it really necessary to lock the Guid like that to prevent torn reads? (I'm pretty sure it is.)
是的.
2)这是进行锁定的合理方法吗?
2) Is that a reasonable way to do the locking?
再次:是.
如果存在Guid
的Interlocked
方法,那会更好(更快).
If there had existed an Interlocked
method for Guid
then that would have been better (faster).
对于double
(另一个非原子结构),Interlocked
提供了支持,而对于引用则不需要.
For double
(another non-atomic struct) there is support from Interlocked
and for references it is not needed.
因此,作为一种模式,仅当Interlocked
不支持的较大结构时才需要.
So as a pattern this is only required for larger structs that are not supported by Interlocked
.
这篇关于使Guid属性成为线程安全的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!