35 lines
973 B
C#
35 lines
973 B
C#
![]() |
using System.Threading;
|
|||
|
using System.Threading.Tasks;
|
|||
|
|
|||
|
namespace SWS.CAD.Models.NoEntity
|
|||
|
{
|
|||
|
/// <summary>
|
|||
|
/// 搜索框防抖类
|
|||
|
/// </summary>
|
|||
|
public class Debouncer
|
|||
|
{
|
|||
|
private readonly int _delayMilliseconds;
|
|||
|
private CancellationTokenSource _cancellationTokenSource;
|
|||
|
|
|||
|
public Debouncer(int delayMilliseconds = 300)
|
|||
|
{
|
|||
|
_delayMilliseconds = delayMilliseconds;
|
|||
|
}
|
|||
|
|
|||
|
public void Debounce(System.Action action)
|
|||
|
{
|
|||
|
_cancellationTokenSource?.Cancel();
|
|||
|
_cancellationTokenSource = new CancellationTokenSource();
|
|||
|
|
|||
|
Task.Delay(_delayMilliseconds, _cancellationTokenSource.Token)
|
|||
|
.ContinueWith(t =>
|
|||
|
{
|
|||
|
if (t.IsCompleted && !t.IsCanceled)
|
|||
|
{
|
|||
|
action?.Invoke();
|
|||
|
}
|
|||
|
}, TaskScheduler.FromCurrentSynchronizationContext());
|
|||
|
}
|
|||
|
}
|
|||
|
}
|