forked from Excel-DNA/IntelliSense
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRenewableDelayExecutor.cs
67 lines (55 loc) · 1.64 KB
/
RenewableDelayExecutor.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
using System;
using System.Timers;
namespace ExcelDna.IntelliSense.Util
{
/// <summary>
/// Upon a signal, executes the specified action after the specified delay.
/// If any other signal arrives during the waiting period, the delay interval begins anew.
/// </summary>
internal class RenewableDelayExecutor : IDisposable
{
private readonly Timer _timer;
private readonly Action _action;
private readonly int _debounceIntervalMilliseconds;
public bool IsDisposed { get; private set; }
public RenewableDelayExecutor(int debounceIntervalMilliseconds, Action action)
{
_action = action;
_debounceIntervalMilliseconds = debounceIntervalMilliseconds;
_timer = new Timer
{
AutoReset = false,
Interval = _debounceIntervalMilliseconds,
};
_timer.Elapsed += OnTimerElapsed;
}
private void OnTimerElapsed(object sender, ElapsedEventArgs e)
{
if (IsDisposed)
{
return;
}
_action();
}
public void Signal()
{
_timer.Stop();
_timer.Start();
}
private void Dispose(bool isDisposing)
{
IsDisposed = true;
_timer.Elapsed -= OnTimerElapsed;
_timer.Dispose();
if (isDisposing)
{
GC.SuppressFinalize(this);
}
}
public void Dispose() => Dispose(true);
~RenewableDelayExecutor()
{
Dispose(false);
}
}
}