InterlockedBoolean.cs
1 // Copyright (c) Microsoft Corporation 2 // The Microsoft Corporation licenses this file to you under the MIT license. 3 // See the LICENSE file in the project root for more information. 4 5 using System.Threading; 6 7 namespace Microsoft.CmdPal.Core.Common.Helpers; 8 9 /// <summary> 10 /// Thread-safe boolean implementation using atomic operations 11 /// </summary> 12 public struct InterlockedBoolean(bool initialValue = false) 13 { 14 private int _value = initialValue ? 1 : 0; 15 16 /// <summary> 17 /// Gets or sets the boolean value atomically 18 /// </summary> 19 public bool Value 20 { 21 get => Volatile.Read(ref _value) == 1; 22 set => Interlocked.Exchange(ref _value, value ? 1 : 0); 23 } 24 25 /// <summary> 26 /// Atomically sets the value to true 27 /// </summary> 28 /// <returns>True if the value was previously false, false if it was already true</returns> 29 public bool Set() 30 { 31 return Interlocked.Exchange(ref _value, 1) == 0; 32 } 33 34 /// <summary> 35 /// Atomically sets the value to false 36 /// </summary> 37 /// <returns>True if the value was previously true, false if it was already false</returns> 38 public bool Clear() 39 { 40 return Interlocked.Exchange(ref _value, 0) == 1; 41 } 42 43 public override int GetHashCode() => Value.GetHashCode(); 44 45 public override string ToString() => Value.ToString(); 46 }