在bool值上使用Interlocked.CompareExchange()操作? [英] Using Interlocked.CompareExchange() operation on a bool value?

查看:136
本文介绍了在bool值上使用Interlocked.CompareExchange()操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个问题:

  1. 是否需要使用Interlocked类访问布尔值?默认情况下,不是对布尔值atom进行读取或写入吗?

  1. 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 ?

推荐答案

  1. 分别读取或写入布尔值原子的,但是比较和交换"会同时读取和写入同一地址,这意味着整个交易不是 原子.如果多个线程可以写入同一位置,则需要使用Interlocked类使整个事务具有原子性.

  1. 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()操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆