56 lines
1.1 KiB
C#
56 lines
1.1 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
|
|
namespace BITKit
|
|
{
|
|
/// <summary>
|
|
/// 双缓冲区
|
|
/// </summary>
|
|
/// <typeparam name="T"></typeparam>
|
|
public interface IDoubleBuffer<T>
|
|
{
|
|
bool CanRelease { get; }
|
|
T Current { get; }
|
|
void Release(T newValue);
|
|
event Action<T> OnRelease;
|
|
bool TryGetRelease(out T result);
|
|
}
|
|
/// <summary>
|
|
/// <see cref="IDoubleBuffer{T}"/>
|
|
/// </summary>
|
|
/// <typeparam name="T"></typeparam>
|
|
public class DoubleBuffer<T> : IDoubleBuffer<T>
|
|
{
|
|
public bool CanRelease => _release.Allow;
|
|
|
|
public T Current
|
|
{
|
|
get;
|
|
// ReSharper disable once MemberCanBePrivate.Global
|
|
protected set;
|
|
}
|
|
|
|
public void Release(T newValue)
|
|
{
|
|
Current = newValue;
|
|
OnRelease?.Invoke(newValue);
|
|
_release.SetValueThenAllow(newValue);
|
|
}
|
|
|
|
public void Clear()
|
|
{
|
|
_release.Clear();
|
|
}
|
|
|
|
public event Action<T> OnRelease;
|
|
private readonly Optional<T> _release=new();
|
|
|
|
public bool TryGetRelease(out T result)
|
|
{
|
|
result = _release.Value;
|
|
if (!_release.Allow) return _release.Allow;
|
|
_release.Clear();
|
|
return true;
|
|
}
|
|
}
|
|
} |