microsoft/teams.net
Publicmirrored fromhttps://github.com/microsoft/teams.netAvailable
Libraries/Microsoft.Teams.Common/Extensions/ActionExtensions.cs
44lines · modecode
| 1 | namespace Microsoft.Teams.Common.Extensions; |
| 2 | |
| 3 | public static class ActionExtensions |
| 4 | { |
| 5 | public static Action<T> Debounce<T>(this Action<T> func, int milliseconds = 300) |
| 6 | { |
| 7 | CancellationTokenSource? cancelTokenSource = null; |
| 8 | |
| 9 | return arg => |
| 10 | { |
| 11 | cancelTokenSource?.Cancel(); |
| 12 | cancelTokenSource = new CancellationTokenSource(); |
| 13 | |
| 14 | Task.Delay(milliseconds, cancelTokenSource.Token) |
| 15 | .ContinueWith(t => |
| 16 | { |
| 17 | if (t.IsCompleted && !t.IsFaulted) |
| 18 | { |
| 19 | func(arg); |
| 20 | } |
| 21 | }, TaskScheduler.Default); |
| 22 | }; |
| 23 | } |
| 24 | |
| 25 | public static Action Debounce(this Func<Task> func, int milliseconds = 300) |
| 26 | { |
| 27 | CancellationTokenSource? cancelTokenSource = null; |
| 28 | |
| 29 | return () => |
| 30 | { |
| 31 | cancelTokenSource?.Cancel(); |
| 32 | cancelTokenSource = new CancellationTokenSource(); |
| 33 | |
| 34 | Task.Delay(milliseconds, cancelTokenSource.Token) |
| 35 | .ContinueWith(async t => |
| 36 | { |
| 37 | if (t.IsCompleted && !t.IsFaulted) |
| 38 | { |
| 39 | await func(); |
| 40 | } |
| 41 | }, TaskScheduler.Default); |
| 42 | }; |
| 43 | } |
| 44 | } |