You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

SafeValueOther.cs 1.2 kB

12345678910111213141516171819202122232425262728
  1. using System;
  2. using System.Threading;
  3. namespace Preparation.Utility
  4. {
  5. //其对应属性不应当有set访问器,避免不安全的=赋值
  6. public class AtomicBool
  7. {
  8. private int v;//v==0为false,v==1为true
  9. public AtomicBool(bool x)
  10. {
  11. v = x ? 1 : 0;
  12. }
  13. public override string ToString() => (Interlocked.CompareExchange(ref v, -2, -2) == 0) ? "false" : "true";
  14. public bool Get() => (Interlocked.CompareExchange(ref v, -1, -1) != 0);
  15. public static implicit operator bool(AtomicBool abool) => (Interlocked.CompareExchange(ref abool.v, -1, -1) != 0);
  16. /// <returns>返回操作前的值</returns>
  17. public bool SetReturnOri(bool value) => (Interlocked.Exchange(ref v, value ? 1 : 0) != 0);
  18. /// <returns>赋值前的值是否与将赋予的值不相同</returns>
  19. public bool TrySet(bool value)
  20. {
  21. return (Interlocked.CompareExchange(ref v, value ? 1 : 0, value ? 0 : 1) ^ (value ? 1 : 0)) != 0;
  22. }
  23. public bool And(bool x) => Interlocked.And(ref v, x ? 1 : 0) != 0;
  24. public bool Or(bool x) => Interlocked.Or(ref v, x ? 1 : 0) != 0;
  25. }
  26. }