@@ -8,14 +8,21 @@ namespace ScreenFrame.Helper;
88/// </summary>
99internal class Throttle
1010{
11- private static readonly TimeSpan _dueTime = TimeSpan . FromSeconds ( 0.2 ) ;
12- private readonly Action _action ;
11+ protected readonly TimeSpan _dueTime ;
12+ protected readonly Action _action ;
1313
14- public Throttle ( Action action ) => this . _action = action ;
14+ public Throttle ( TimeSpan dueTime , Action action )
15+ {
16+ if ( dueTime <= TimeSpan . Zero )
17+ throw new ArgumentOutOfRangeException ( nameof ( dueTime ) , dueTime , "The time must be positive." ) ;
18+
19+ this . _dueTime = dueTime ;
20+ this . _action = action ;
21+ }
1522
16- private Task _lastWaitTask ;
23+ protected Task _lastWaitTask ;
1724
18- public async Task PushAsync ( )
25+ public virtual async Task PushAsync ( )
1926 {
2027 var currentWaitTask = Task . Delay ( _dueTime ) ;
2128 _lastWaitTask = currentWaitTask ;
@@ -29,14 +36,21 @@ public async Task PushAsync()
2936
3037internal class Throttle < T >
3138{
32- private static readonly TimeSpan _dueTime = TimeSpan . FromSeconds ( 0.2 ) ;
33- private readonly Action < T > _action ;
39+ protected readonly TimeSpan _dueTime ;
40+ protected readonly Action < T > _action ;
41+
42+ public Throttle ( TimeSpan dueTime , Action < T > action )
43+ {
44+ if ( dueTime <= TimeSpan . Zero )
45+ throw new ArgumentOutOfRangeException ( nameof ( dueTime ) , dueTime , "The time must be positive." ) ;
3446
35- public Throttle ( Action < T > action ) => this . _action = action ;
47+ this . _dueTime = dueTime ;
48+ this . _action = action ;
49+ }
3650
37- private Task _lastWaitTask ;
51+ protected Task _lastWaitTask ;
3852
39- public async Task PushAsync ( T value )
53+ public virtual async Task PushAsync ( T value )
4054 {
4155 var currentWaitTask = Task . Delay ( _dueTime ) ;
4256 _lastWaitTask = currentWaitTask ;
@@ -46,4 +60,24 @@ public async Task PushAsync(T value)
4660 _action ? . Invoke ( value ) ;
4761 }
4862 }
63+ }
64+
65+ /// <summary>
66+ /// Rx Sample like operator
67+ /// </summary>
68+ internal class Sample : Throttle
69+ {
70+ public Sample ( TimeSpan dueTime , Action action ) : base ( dueTime , action )
71+ { }
72+
73+ public override async Task PushAsync ( )
74+ {
75+ if ( _lastWaitTask is not null )
76+ return ;
77+
78+ _lastWaitTask = Task . Delay ( _dueTime ) ;
79+ await _lastWaitTask ;
80+ _action ? . Invoke ( ) ;
81+ _lastWaitTask = null ;
82+ }
4983}
0 commit comments