问题描述
我有两个问题:
-
是否需要使用Interlocked类访问布尔值?默认情况下,不是对布尔值atom进行读取或写入吗?
Is there a need to use Interlocked class for accessing boolean values? Isnt a read or a write to a boolean value atomic by default?
我尝试在布尔值上使用Interlocked.CompareExchange并收到以下错误:
I tried using Interlocked.CompareExchange on a boolean and got the following error:
bool value = true;
Interlocked.CompareExchange<bool>(ref value, false, true);
错误:类型'bool'必须是引用类型,才能在通用类型或方法'System.Threading.Interlocked.CompareExchange(ref T,T,T)'中用作参数'T'
Error: The type 'bool' must be a reference type in order to use it as parameter 'T' in the generic type or method 'System.Threading.Interlocked.CompareExchange(ref T, T, T)'
我该如何解决这个问题?
How do i go about solving this problem ?
推荐答案
-
分别读取或写入布尔值是原子的,但是比较和交换"会同时读取和写入同一地址,这意味着整个交易不是 强>原子.如果多个线程可以写入同一位置,则需要使用
Interlocked
类使整个事务具有原子性.
Reading or writing boolean values separately is atomic, but "compare and exchange" does both reading and writing to the same address, which means that entire transaction is not atomic. If multiple threads can write to this same location, you need to make the entire transaction atomic, by using the
Interlocked
class.
public static T CompareExchange<T>(ref T a, T b, T c)) where T : class
重载只能与引用类型一起使用(请注意最后的where T : class
子句).代替布尔值,可以使用CompareExchange(Int32, Int32, Int32)
重载,并用Int32
切换布尔值.
public static T CompareExchange<T>(ref T a, T b, T c)) where T : class
overload can only be used with reference types (note the where T : class
clause at the end). Instead of a boolean value, you can use the CompareExchange(Int32, Int32, Int32)
overload, and switch the boolean with an Int32
.
或者,如果要保留布尔类型的变量,则可以使用lock
方法来确保线程安全.这将是一个稍微较慢的解决方案,但是根据您的性能要求,这可能仍然是首选方法.
Alternatively, if you want to keep your variables of boolean type, you can use the lock
method to ensure thread safety. This would be a slightly slower solution, but depending on your performance requirements, this might be still the preferred way.
这篇关于在bool值上使用Interlocked.CompareExchange()操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!