FileSearchWindows/FileSearch/Logic/Model/Engine/TimedCallback.cs
Dvurechensky e2bffc8b49 1.0
Main
2024-10-05 10:06:04 +03:00

47 lines
1.6 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

namespace FileSearch.Logic.Model.Engine
{
internal class TimedCallback<T>
{
private readonly TimeSpan _timeout;
private readonly Action<IEnumerable<T>> _callback;
private DateTime _lastTrigger;
private bool _isRunning = false;
public TimedCallback(TimeSpan timeout, Action<IEnumerable<T>> callback)
{
if (callback == null) throw new ArgumentNullException("callback");
if (timeout.TotalSeconds < 0.1) throw new ArgumentException(@"The timeout should be minimal 0.1 second.", "timeout");
_timeout = timeout;
_callback = callback;
_lastTrigger = DateTime.UtcNow;
}
/// <summary>
/// Значение, указывающее, превышен ли период тайм-аута и можно ли получить новые данные.
/// </summary>
public bool DataNeeded
{
get { return !_isRunning && DateTime.UtcNow - _lastTrigger >= _timeout; }
}
/// <summary>
/// Устанавливает данные для отправки делегату обратного вызова.
/// </summary>
/// <param name="collection">Сбор с данными.</param>
public void SetData(IEnumerable<T> collection)
{
try
{
_isRunning = true;
_callback(collection);
_lastTrigger = DateTime.UtcNow;
}
finally
{
_isRunning = false;
}
}
}
}