BITKit/Src/Core/DesignPatterns/DoubleBuffer.cs

56 lines
1.1 KiB
C#
Raw Normal View History

2023-07-17 10:23:47 +08:00
using System;
using System.Collections.Generic;
namespace BITKit
{
2023-10-06 23:43:19 +08:00
/// <summary>
/// 双缓冲区
/// </summary>
/// <typeparam name="T"></typeparam>
2023-07-17 10:23:47 +08:00
public interface IDoubleBuffer<T>
{
2023-10-24 23:38:22 +08:00
bool CanRelease { get; }
2023-07-17 10:23:47 +08:00
T Current { get; }
void Release(T newValue);
event Action<T> OnRelease;
bool TryGetRelease(out T result);
}
2023-10-06 23:43:19 +08:00
/// <summary>
/// <see cref="IDoubleBuffer{T}"/>
/// </summary>
/// <typeparam name="T"></typeparam>
2023-07-17 10:23:47 +08:00
public class DoubleBuffer<T> : IDoubleBuffer<T>
{
2023-10-24 23:38:22 +08:00
public bool CanRelease => _release.Allow;
2023-07-17 10:23:47 +08:00
public T Current
{
get;
// ReSharper disable once MemberCanBePrivate.Global
protected set;
}
public void Release(T newValue)
{
Current = newValue;
OnRelease?.Invoke(newValue);
2023-10-06 23:43:19 +08:00
_release.SetValueThenAllow(newValue);
2023-07-17 10:23:47 +08:00
}
2023-10-24 23:38:22 +08:00
public void Clear()
{
_release.Clear();
}
2023-07-17 10:23:47 +08:00
public event Action<T> OnRelease;
2023-10-06 23:43:19 +08:00
private readonly Optional<T> _release=new();
2023-07-17 10:23:47 +08:00
public bool TryGetRelease(out T result)
{
2023-10-06 23:43:19 +08:00
result = _release.Value;
if (!_release.Allow) return _release.Allow;
_release.Clear();
return true;
2023-07-17 10:23:47 +08:00
}
}
}