RaspberryIO_26/Swan.Lite/Threading/AtomicEnum.cs

38 lines
1.1 KiB
C#
Raw Permalink Normal View History

2019-12-04 18:57:18 +01:00
using System;
using System.Threading;
2019-12-08 19:54:52 +01:00
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;
2019-12-04 18:57:18 +01:00
/// <summary>
2019-12-08 19:54:52 +01:00
/// Initializes a new instance of the <see cref="AtomicEnum{T}"/> class.
2019-12-04 18:57:18 +01:00
/// </summary>
2019-12-08 19:54:52 +01:00
/// <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);
}
}
2019-12-04 18:57:18 +01:00
}