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