microsoft/teams.net

Public

mirrored fromhttps://github.com/microsoft/teams.netAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
feature/oauthflow-fixes

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

Libraries/Microsoft.Teams.Common/Extensions/ActionExtensions.cs

68lines · modecode

1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the MIT License.
3
4namespace Microsoft.Teams.Common.Extensions;
5
6public 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?.Dispose();
16 cancelTokenSource = new CancellationTokenSource();
17
18 _ = Task.Delay(milliseconds, cancelTokenSource.Token)
19 .ContinueWith(t =>
20 {
21 if (t.IsCompletedSuccessfully)
22 {
23 try
24 {
25 func(arg);
26 }
27 catch
28 {
29 // Observe exception to prevent UnobservedTaskException.
30 // Callers use fire-and-forget; there is no upstream to propagate to.
31 }
32 }
33 }, TaskScheduler.Default);
34 };
35 }
36
37 public static Action Debounce(this Func<Task> func, int milliseconds = 300)
38 {
39 CancellationTokenSource? cancelTokenSource = null;
40
41 return () =>
42 {
43 cancelTokenSource?.Cancel();
44 cancelTokenSource?.Dispose();
45 cancelTokenSource = new CancellationTokenSource();
46
47 _ = DebounceCore(func, milliseconds, cancelTokenSource.Token);
48 };
49
50 static async Task DebounceCore(Func<Task> func, int milliseconds, CancellationToken token)
51 {
52 try
53 {
54 await Task.Delay(milliseconds, token).ConfigureAwait(false);
55 await func().ConfigureAwait(false);
56 }
57 catch (OperationCanceledException)
58 {
59 // Debounce was cancelled by a newer invocation
60 }
61 catch (Exception)
62 {
63 // Observe exception to prevent UnobservedTaskException.
64 // Callers use fire-and-forget; there is no upstream to propagate to.
65 }
66 }
67 }
68}
69