RaspberryIO_26/Swan.Lite/Threading/AtomicEnum.cs
2019-12-08 19:54:52 +01:00

38 lines
1.1 KiB
C#

using System;
using System.Threading;
namespace Swan.Threading {
/// <summary>
/// Defines an atomic generic Enum.
/// </summary>
/// <typeparam name="T">The type of enum.</typeparam>
public sealed class AtomicEnum<T> where T : struct, IConvertible {
private Int64 _backingValue;
/// <summary>
/// Initializes a new instance of the <see cref="AtomicEnum{T}"/> class.
/// </summary>
/// <param name="initialValue">The initial value.</param>
/// <exception cref="ArgumentException">T must be an enumerated type.</exception>
public AtomicEnum(T initialValue) {
if(!Enum.IsDefined(typeof(T), initialValue)) {
throw new ArgumentException("T must be an enumerated type");
}
this.Value = initialValue;
}
/// <summary>
/// Gets or sets the value.
/// </summary>
public T Value {
get => (T)Enum.ToObject(typeof(T), this.BackingValue);
set => this.BackingValue = Convert.ToInt64(value);
}
private Int64 BackingValue {
get => Interlocked.Read(ref this._backingValue);
set => Interlocked.Exchange(ref this._backingValue, value);
}
}
}