├── Assets ├── icon.png ├── debounce_marble.png └── icon.svg ├── Directory.Build.props ├── DebounceMonitoring ├── Ref.cs ├── DebounceMonitoring.csproj ├── ObjectTimeStamps.cs ├── ObservableDebounceDecorator.cs ├── ObservableDebounceExtensions.cs └── DebounceMonitor.cs ├── DebounceMonitoring.Tests ├── Models.cs ├── DebounceMonitoring.Tests.csproj ├── ObservableDebounceTest.cs ├── IntervalTest.cs ├── Snippets │ └── Sample.cs └── DebounceHereTest.cs ├── LICENSE ├── .github └── workflows │ └── ci.yml ├── DebounceMonitoring.sln ├── .gitattributes ├── README.md └── .gitignore /Assets/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SIDOVSKY/DebounceMonitoring/HEAD/Assets/icon.png -------------------------------------------------------------------------------- /Assets/debounce_marble.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SIDOVSKY/DebounceMonitoring/HEAD/Assets/debounce_marble.png -------------------------------------------------------------------------------- /Directory.Build.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | enable 4 | 9.0 5 | 6 | -------------------------------------------------------------------------------- /DebounceMonitoring/Ref.cs: -------------------------------------------------------------------------------- 1 | namespace DebounceMonitoring 2 | { 3 | internal class Ref where T : struct 4 | { 5 | public T Value; 6 | 7 | public Ref(T value = default) 8 | { 9 | Value = value; 10 | } 11 | 12 | public override string ToString() => Value.ToString(); 13 | } 14 | } -------------------------------------------------------------------------------- /DebounceMonitoring.Tests/Models.cs: -------------------------------------------------------------------------------- 1 | namespace DebounceMonitoring.Tests 2 | { 3 | public class DebouncingSample 4 | { 5 | public static bool DebounceDuring100msStatic() 6 | { 7 | return DebounceMonitor.DebounceHereStatic(100); 8 | } 9 | 10 | public bool DebounceDuring100ms() 11 | { 12 | return this.DebounceHere(100); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /DebounceMonitoring.Tests/DebounceMonitoring.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | false 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /DebounceMonitoring/DebounceMonitoring.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | true 6 | SIDOVSKY 7 | MIT 8 | https://github.com/SIDOVSKY/DebounceMonitoring 9 | https://github.com/SIDOVSKY/DebounceMonitoring.git 10 | git 11 | Vadim Sedov 12 | icon.png 13 | debounce, throttle, click, touch, ui 14 | 1.0.1 15 | 📑 Add debounce logic for any method in a single line. 16 | Thread-safety improvements 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /DebounceMonitoring.Tests/ObservableDebounceTest.cs: -------------------------------------------------------------------------------- 1 | using System.Reactive.Linq; 2 | using System.Threading.Tasks; 3 | using Xunit; 4 | 5 | namespace DebounceMonitoring.Tests 6 | { 7 | public class ObservableDebounceTest 8 | { 9 | [Fact] 10 | public async void Interval_Should_Not_Slide_With_Each_Call() 11 | { 12 | Assert.Equal( 13 | new[] { 0, 110, 220 }, 14 | await Observable.Create(async o => 15 | { 16 | o.OnNext(0); 17 | await Task.Delay(50); 18 | o.OnNext(50); // too fast 19 | await Task.Delay(60); 20 | o.OnNext(110); // 50 + 60 > 100, OK 21 | await Task.Delay(50); 22 | o.OnNext(160); 23 | await Task.Delay(60); 24 | o.OnNext(220); 25 | }) 26 | .Debounce(intervalMs: 100) 27 | .ToList()); 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Vadim Sedov 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | paths-ignore: 8 | - '**/*.md' 9 | pull_request: 10 | paths-ignore: 11 | - '**/*.md' 12 | 13 | jobs: 14 | main: 15 | name: Build, Test 16 | runs-on: ubuntu-latest 17 | steps: 18 | - name: Checkout code 19 | uses: actions/checkout@v2 20 | 21 | - name: Test 22 | id: unit-test 23 | run: | 24 | dotnet test --logger "trx;LogFileName=UnitTestResults.trx" 25 | 26 | - name: Prepare Unit Test Results 27 | id: prepare-unit-test-results 28 | if: ${{ !cancelled() && (steps.unit-test.outcome == 'success' || steps.unit-test.outcome == 'failure') }} 29 | run: | 30 | dotnet tool install --global trx2junit 31 | trx2junit ./DebounceMonitoring.Tests/TestResults/UnitTestResults.trx 32 | 33 | - name: Publish Unit Test Results 34 | if: ${{ !cancelled() && steps.prepare-unit-test-results.outcome == 'success' }} 35 | uses: docker://ghcr.io/enricomi/publish-unit-test-result-action:v1.9 36 | with: 37 | github_token: ${{ github.token }} 38 | files: ./DebounceMonitoring.Tests/TestResults/UnitTestResults.xml 39 | check_name: Unit Test Results 40 | comment_on_pr: false -------------------------------------------------------------------------------- /DebounceMonitoring/ObjectTimeStamps.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Runtime.CompilerServices; 3 | 4 | namespace DebounceMonitoring 5 | { 6 | internal class ObjectTimeStamps 7 | { 8 | private readonly object _lock = new(); 9 | private ConditionalWeakTable>? _manyObjectStamps; 10 | private WeakReference? _singleRef; 11 | private DateTime _singleRefStamp; 12 | 13 | public ref DateTime GetOrAddRef(object obj) 14 | { 15 | lock (_lock) 16 | { 17 | if (_manyObjectStamps is not null) 18 | return ref _manyObjectStamps.GetValue(obj, createValueCallback: _ => new()).Value; 19 | 20 | if (_singleRef?.Target is not object singleObject) 21 | { 22 | _singleRef = new WeakReference(singleObject = obj); 23 | } 24 | 25 | if (singleObject == obj) 26 | return ref _singleRefStamp; 27 | 28 | var newStamp = new Ref(); 29 | 30 | // Transform into the multi-object mode 31 | _manyObjectStamps = new ConditionalWeakTable>(); 32 | _manyObjectStamps.Add(singleObject, new Ref(_singleRefStamp)); 33 | _manyObjectStamps.Add(obj, newStamp); 34 | 35 | _singleRef = null; 36 | 37 | return ref newStamp.Value; 38 | } 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /DebounceMonitoring.Tests/IntervalTest.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using Xunit; 3 | 4 | namespace DebounceMonitoring.Tests 5 | { 6 | public class IntervalTest 7 | { 8 | [Fact] 9 | public void Should_Return_True_For_Delay_Withing_Interval() 10 | { 11 | var sample = new DebouncingSample(); 12 | 13 | Assert.False(sample.DebounceDuring100ms()); 14 | Assert.True(sample.DebounceDuring100ms()); 15 | } 16 | 17 | [Fact] 18 | public async Task Should_Return_False_For_Delay_Over_Interval() 19 | { 20 | var sample = new DebouncingSample(); 21 | 22 | Assert.False(sample.DebounceDuring100ms()); 23 | 24 | await Task.Delay(110).ConfigureAwait(false); 25 | 26 | Assert.False(sample.DebounceDuring100ms()); 27 | } 28 | 29 | [Fact] 30 | public async Task Interval_Should_Not_Slide_With_Each_Call() 31 | { 32 | var sample = new DebouncingSample(); 33 | 34 | Assert.False(sample.DebounceDuring100ms()); 35 | 36 | await Task.Delay(50).ConfigureAwait(false); 37 | Assert.True(sample.DebounceDuring100ms()); 38 | 39 | await Task.Delay(60).ConfigureAwait(false); 40 | Assert.False(sample.DebounceDuring100ms()); 41 | 42 | await Task.Delay(50).ConfigureAwait(false); 43 | Assert.True(sample.DebounceDuring100ms()); 44 | 45 | await Task.Delay(60).ConfigureAwait(false); 46 | Assert.False(sample.DebounceDuring100ms()); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /DebounceMonitoring/ObservableDebounceDecorator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace DebounceMonitoring 4 | { 5 | internal class ObservableDebounceDecorator : IObservable, IObserver, IDisposable 6 | { 7 | private readonly TimeSpan _interval; 8 | private readonly IObservable _source; 9 | 10 | private DateTime _lastStamp; 11 | private IObserver? _observer; 12 | private IDisposable? _sourceDisposable; 13 | 14 | public ObservableDebounceDecorator(IObservable source, TimeSpan interval) 15 | { 16 | _source = source; 17 | _interval = interval; 18 | } 19 | 20 | public IDisposable Subscribe(IObserver observer) 21 | { 22 | _observer = observer; 23 | _sourceDisposable = _source.Subscribe(this); 24 | return this; 25 | } 26 | 27 | public void OnCompleted() => _observer?.OnCompleted(); 28 | 29 | public void OnError(Exception error) => _observer?.OnError(error); 30 | 31 | public void OnNext(T value) 32 | { 33 | if (!DebounceMonitor.Disabled) 34 | { 35 | var now = DateTime.UtcNow; 36 | 37 | if (now < _lastStamp + _interval) 38 | return; 39 | 40 | _lastStamp = now; 41 | } 42 | 43 | _observer?.OnNext(value); 44 | } 45 | public void Dispose() 46 | { 47 | _sourceDisposable?.Dispose(); 48 | _sourceDisposable = null; 49 | _observer = null; 50 | } 51 | } 52 | } -------------------------------------------------------------------------------- /DebounceMonitoring/ObservableDebounceExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace DebounceMonitoring 4 | { 5 | /// 6 | /// Provides a set of static methods for debouncing observable sequences. 7 | /// 8 | public static class ObservableDebounceExtensions 9 | { 10 | /// 11 | /// Emits only the first item emitted by the source within periodic time intervals. 12 | /// 13 | /// 14 | /// Marble diagram 15 | /// (image): 16 | /// 17 | /// -A----B-C-------D-----E-|-->
18 | /// -a~~~~~~~~~1s---d~~~~~~~|-->
19 | /// -A--------------D-------|-->
20 | ///
21 | ///
22 | /// Interactive 23 | /// (throttle in RxJs) 24 | ///
25 | /// The type of the elements in the source sequence. 26 | /// An observable sequence whose elements to debounce. 27 | /// 28 | /// Time to wait before emitting another item after emitting the last one. 29 | /// Defaults to if not specified. 30 | /// 31 | /// an that performs the debounce operation 32 | public static IObservable Debounce(this IObservable source, int? intervalMs = null) 33 | { 34 | var interval = intervalMs.HasValue 35 | ? TimeSpan.FromMilliseconds(intervalMs.Value) 36 | : DebounceMonitor.DefaultInterval; 37 | 38 | return new ObservableDebounceDecorator(source, interval); 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /DebounceMonitoring.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.30907.101 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DebounceMonitoring", "DebounceMonitoring\DebounceMonitoring.csproj", "{388A7042-C1D0-4C3C-B938-CD4E64190D78}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DebounceMonitoring.Tests", "DebounceMonitoring.Tests\DebounceMonitoring.Tests.csproj", "{70CC6D31-E0AD-4E45-AE4E-4034A384D97A}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{C491947A-1E1D-4B5B-885D-B130ED4AFCFD}" 11 | ProjectSection(SolutionItems) = preProject 12 | Directory.Build.props = Directory.Build.props 13 | README.md = README.md 14 | EndProjectSection 15 | EndProject 16 | Global 17 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 18 | Debug|Any CPU = Debug|Any CPU 19 | Release|Any CPU = Release|Any CPU 20 | EndGlobalSection 21 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 22 | {388A7042-C1D0-4C3C-B938-CD4E64190D78}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {388A7042-C1D0-4C3C-B938-CD4E64190D78}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {388A7042-C1D0-4C3C-B938-CD4E64190D78}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {388A7042-C1D0-4C3C-B938-CD4E64190D78}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {70CC6D31-E0AD-4E45-AE4E-4034A384D97A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {70CC6D31-E0AD-4E45-AE4E-4034A384D97A}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {70CC6D31-E0AD-4E45-AE4E-4034A384D97A}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {70CC6D31-E0AD-4E45-AE4E-4034A384D97A}.Release|Any CPU.Build.0 = Release|Any CPU 30 | EndGlobalSection 31 | GlobalSection(SolutionProperties) = preSolution 32 | HideSolutionNode = FALSE 33 | EndGlobalSection 34 | GlobalSection(ExtensibilityGlobals) = postSolution 35 | SolutionGuid = {463C77CD-EDBB-4DCB-B6EF-BB7AB7D87A89} 36 | EndGlobalSection 37 | EndGlobal 38 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /DebounceMonitoring.Tests/Snippets/Sample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Reactive.Linq; 3 | using System.Windows.Input; 4 | 5 | #pragma warning disable CS0067 // The event is never used 6 | 7 | namespace DebounceMonitoring.Tests.Snippets 8 | { 9 | internal class ViewModel 10 | { 11 | public void OnButtonClick() 12 | { 13 | if (this.DebounceHere()) return; 14 | 15 | // Handle the click 16 | } 17 | 18 | public Command ClickCommand { get; } 19 | 20 | public ViewModel() 21 | { 22 | ClickCommand = new Command(() => 23 | { 24 | if (this.DebounceHere()) return; 25 | 26 | // Handle the click 27 | }); 28 | } 29 | 30 | public void ObservableDebounce(Button button) 31 | { 32 | button.ClickAsObservable() 33 | .Debounce() 34 | .Subscribe(_ => OnButtonClick()); 35 | } 36 | 37 | public void MultipleObjectsOneMethod() 38 | { 39 | new Button().Click += OnClick; 40 | new Button().Click += OnClick; 41 | new Button().Click += OnClick; 42 | 43 | void OnClick(object? sender, EventArgs e) 44 | { 45 | if (this.DebounceHere()) return; // NOT RECOMMENDED! 46 | if (sender!.DebounceHere()) return; 47 | 48 | // Handle the click 49 | } 50 | } 51 | } 52 | 53 | internal class Analytics 54 | { 55 | public static void TrackEvent() 56 | { 57 | if (DebounceMonitor.DebounceHereStatic()) return; 58 | 59 | // The logic 60 | } 61 | } 62 | 63 | internal static class UnitTestGlobalSetup 64 | { 65 | //[System.Runtime.CompilerServices.ModuleInitializer] 66 | internal static void SetupDebounceMonitor() => DebounceMonitor.Disabled = true; 67 | } 68 | 69 | internal class Button 70 | { 71 | public event EventHandler? Click; 72 | } 73 | 74 | internal static class ButtonRxExtensions 75 | { 76 | public static IObservable ClickAsObservable(this Button self) 77 | { 78 | return Observable.FromEvent( 79 | h => (s, e) => h(e), 80 | h => self.Click += h, 81 | h => self.Click -= h); 82 | } 83 | } 84 | 85 | internal class Command : ICommand 86 | { 87 | private readonly Action _action; 88 | 89 | public Command(Action action) 90 | { 91 | _action = action; 92 | } 93 | 94 | public event EventHandler? CanExecuteChanged; 95 | public bool CanExecute(object? parameter) => true; 96 | public void Execute(object? parameter) => _action.Invoke(); 97 | } 98 | } -------------------------------------------------------------------------------- /Assets/icon.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![LOGO](Assets/icon.png) 2 | 3 | # DebounceMonitoring 4 | 5 | [![CI](https://github.com/SIDOVSKY/DebounceMonitoring/actions/workflows/ci.yml/badge.svg)](https://github.com/SIDOVSKY/DebounceMonitoring/actions/workflows/ci.yml) 6 | [![PLATFORM](https://img.shields.io/badge/platform-.NET%20Standard%202.0-lightgrey)](#DebounceMonitoring) 7 | [![NuGet](https://img.shields.io/nuget/v/DebounceMonitoring?logo=nuget)](https://www.nuget.org/packages/DebounceMonitoring/) 8 | 9 | Extensions to filter out repeated function calls caused by false or accidental clicks or touches. 10 | * One-line integration 11 | * Inlined, no method wrapping 12 | * Shareable between multiple platforms 13 | * Automated testing friendly 14 | 15 | ## Installing 16 | 17 | Add [NuGet package](https://www.nuget.org/packages/DebounceMonitoring) to your [.NET Standard 2.0 - compatible](https://github.com/dotnet/standard/blob/master/docs/versions/netstandard2.0.md#platform-support) project 18 | 19 | ``` 20 | PM> Install-Package DebounceMonitoring 21 | ``` 22 | 23 | ## Usage 24 | 25 | ```csharp 26 | using DebounceMonitoring; 27 | ``` 28 | 29 | #### Debounce **instance** methods: 30 | ```csharp 31 | internal class ViewModel 32 | { 33 | public void OnButtonClick() 34 | { 35 | if (this.DebounceHere()) return; 36 | 37 | // Handle the click 38 | } 39 | } 40 | ``` 41 | [snippet source](/DebounceMonitoring.Tests/Snippets/Sample.cs#L9-L16) 42 | 43 | #### Debounce **lambdas** and **local functions**: 44 | ```csharp 45 | public Command ClickCommand { get; } 46 | 47 | public ViewModel() 48 | { 49 | ClickCommand = new Command(() => 50 | { 51 | if (this.DebounceHere()) return; 52 | 53 | // Handle the click 54 | }); 55 | } 56 | ``` 57 | [snippet source](/DebounceMonitoring.Tests/Snippets/Sample.cs#L18-L28) 58 | 59 | #### Debounce **static** methods: 60 | ```csharp 61 | internal class Analytics 62 | { 63 | public static void TrackEvent() 64 | { 65 | if (DebounceMonitor.DebounceHereStatic()) return; 66 | 67 | // Send the event 68 | } 69 | } 70 | ``` 71 | [snippet source](/DebounceMonitoring.Tests/Snippets/Sample.cs#L52-L61) 72 | 73 | ### Rx Operator 74 | 75 | This library also provides the simplest implementation of the debounce operator for [Rx.NET](https://github.com/dotnet/reactive) ([`throttle`](https://rxmarbles.com/#throttle) in RxJs). 76 | 77 | 78 | 79 | Example: 80 | ```csharp 81 | button.ClickAsObservable() 82 | .Debounce() 83 | .Subscribe(_ => OnButtonClick()); 84 | ``` 85 | [snippet source](/DebounceMonitoring.Tests/Snippets/Sample.cs#L32-L34) 86 | 87 | ### Interval 88 | 89 | The default debounce interval is 500 ms. 90 | It can be specified as an argument: 91 | 92 | ```csharp 93 | this.DebounceHere(intervalMs: 1_000) 94 | 95 | IObservable.Debounce(intervalMs: 1_000) 96 | ``` 97 | or set globally: 98 | 99 | ```csharp 100 | DebounceMonitor.DefaultInterval = TimeSpan.FromSeconds(5); 101 | ``` 102 | 103 | ### Disable (for automated testing) 104 | 105 | The `DebounceMonitor` can be disabled in your base `TestFixture.Setup` or globally in `ModuleInitializer` with [ModuleInitializerAttribute](https://docs.microsoft.com/dotnet/api/system.runtime.compilerservices.moduleinitializerattribute) or [Fody.ModuleInit](https://github.com/Fody/ModuleInit). 106 | 107 | ```csharp 108 | internal static class UnitTestGlobalSetup 109 | { 110 | [System.Runtime.CompilerServices.ModuleInitializer] 111 | internal static void SetupDebounceMonitor() => DebounceMonitor.Disabled = true; 112 | } 113 | ``` 114 | [snippet source](/DebounceMonitoring.Tests/Snippets/Sample.cs#L63-L67) 115 | 116 | ## How does it work? 117 | 118 | When `this.DebounceHere` is called, the call time is mapped to its location (method name + line number) and target (`this` in this case). 119 | 120 | On the next call, the time is compared to the stored one. If the `interval` has not yet passed, then the call is meant to be debounced. 121 | 122 | The debounce target (reference) is held weakly, so no memory leaks are caused. 123 | 124 | ## License 125 | 126 | This project is licensed under the MIT license - see the [LICENSE](LICENSE) file for details. -------------------------------------------------------------------------------- /DebounceMonitoring.Tests/DebounceHereTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | using Xunit; 5 | 6 | namespace DebounceMonitoring.Tests 7 | { 8 | public class DebounceHereTest 9 | { 10 | [Fact] 11 | public void Should_Hold_Debounce_References_Weakly() 12 | { 13 | WeakReference? sampleRef = null; 14 | WeakReference? sampleRef2 = null; 15 | 16 | new Action(() => 17 | { 18 | var sample = new DebouncingSample(); 19 | var sample2 = new DebouncingSample(); 20 | 21 | sampleRef = new WeakReference(sample); 22 | sampleRef2 = new WeakReference(sample2); 23 | 24 | sample.DebounceHere(); 25 | sample2.DebounceHere(); 26 | }).Invoke(); 27 | 28 | GC.Collect(); 29 | 30 | Assert.False(sampleRef!.IsAlive); 31 | Assert.False(sampleRef2!.IsAlive); 32 | } 33 | 34 | [Fact] 35 | public void Should_Work_From_Local_Functions() 36 | { 37 | var sample = new DebouncingSample(); 38 | 39 | Assert.False(LocalDebounce(sample)); 40 | Assert.True(LocalDebounce(sample)); 41 | 42 | static bool LocalDebounce(DebouncingSample sample) => sample.DebounceHere(); 43 | } 44 | 45 | [Fact] 46 | public void Should_Work_For_A_Single_Object_At_Multiple_Locations() 47 | { 48 | var sample = new DebouncingSample(); 49 | 50 | Assert.False(DebounceLocation1(sample)); 51 | Assert.False(DebounceLocation2(sample)); 52 | 53 | Assert.True(DebounceLocation1(sample)); 54 | Assert.True(DebounceLocation2(sample)); 55 | 56 | static bool DebounceLocation1(DebouncingSample sample) => sample.DebounceHere(); 57 | static bool DebounceLocation2(DebouncingSample sample) => sample.DebounceHere(); 58 | } 59 | 60 | [Fact] 61 | public void Should_Work_For_Multiple_Objects_At_Same_Location() 62 | { 63 | var sample = new DebouncingSample(); 64 | var sample2 = new DebouncingSample(); 65 | 66 | Assert.False(SameLocationDebounce(sample)); 67 | Assert.False(SameLocationDebounce(sample2)); 68 | Assert.True(SameLocationDebounce(sample)); 69 | Assert.True(SameLocationDebounce(sample2)); 70 | 71 | static bool SameLocationDebounce(DebouncingSample sample) => sample.DebounceHere(); 72 | } 73 | 74 | [Fact] 75 | public void Should_Be_Thread_Safe() 76 | { 77 | var testOk = true; 78 | 79 | var thread1 = new Thread(Test); 80 | var thread2 = new Thread(Test); 81 | 82 | thread1.Start(); 83 | thread2.Start(); 84 | 85 | thread1.Join(); 86 | thread2.Join(); 87 | 88 | Assert.True(testOk); 89 | 90 | void Test() 91 | { 92 | for (int i = 0; i < 100000; i++) 93 | { 94 | var sample = new DebouncingSample(); 95 | var sample2 = new DebouncingSample(); 96 | 97 | testOk &= !sample.DebounceHere(); 98 | testOk &= !sample2.DebounceHere(); 99 | 100 | testOk &= !SameLocationDebounce(sample); 101 | testOk &= !SameLocationDebounce(sample2); 102 | 103 | testOk &= SameLocationDebounce(sample); 104 | testOk &= SameLocationDebounce(sample2); 105 | } 106 | } 107 | 108 | static bool SameLocationDebounce(DebouncingSample sample) => sample.DebounceHere(); 109 | } 110 | 111 | [Fact] 112 | public void Should_Be_Thread_Safe_In_Debouncing_Second_Object_At_The_Same_Location() 113 | { 114 | var allDebounceResultsAsExpected = true; 115 | 116 | var sample = new DebouncingSample(); 117 | 118 | for (int i = 0; i < 10000; i++) 119 | { 120 | SameLocationDebounce(sample); 121 | 122 | Parallel.For(0, 10, new ParallelOptions { MaxDegreeOfParallelism = 10 }, _ => 123 | { 124 | var sample2 = new DebouncingSample(); 125 | allDebounceResultsAsExpected &= !SameLocationDebounce(sample2); 126 | allDebounceResultsAsExpected &= SameLocationDebounce(sample2); 127 | }); 128 | 129 | bool SameLocationDebounce(DebouncingSample sample) => sample.DebounceHere( 130 | memberName: nameof(Should_Be_Thread_Safe_In_Debouncing_Second_Object_At_The_Same_Location), 131 | lineNumber: i); 132 | } 133 | 134 | Assert.True(allDebounceResultsAsExpected, "All debounce results appeared as expected"); 135 | } 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /DebounceMonitoring/DebounceMonitor.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Runtime.CompilerServices; 4 | 5 | namespace DebounceMonitoring 6 | { 7 | /// 8 | /// Attaches a debounce countdown to a reference object (a type for static calls) 9 | /// and the call location (member + line number). 10 | /// 11 | public static class DebounceMonitor 12 | { 13 | /// 14 | /// The initial interval used for all debounce calls when no corresponding parameter is specified. 15 | /// 16 | public const int InitialDefaultIntervalMs = 500; 17 | 18 | private static readonly ConcurrentDictionary _debounceTimeStamps = new(); 19 | 20 | /// 21 | /// An interval used in and 22 | /// when the corresponding parameter is not specified.
23 | ///
24 | /// 25 | /// Initial value is . 26 | /// 27 | public static TimeSpan DefaultInterval { get; set; } = TimeSpan.FromMilliseconds(InitialDefaultIntervalMs); 28 | 29 | /// 30 | /// Make and always return false. 31 | /// 32 | /// 33 | /// Useful for automated tests. May be set globally in ModuleInitializer 34 | /// with ModuleInitializerAttribute 35 | /// or Fody.ModuleInit. 36 | /// 37 | public static bool Disabled { get; set; } 38 | 39 | /// 40 | /// Сhecks whether the call of the current line for the 41 | /// has been repeated within the since the last non-repeating call. 42 | /// 43 | /// 44 | /// Usage: 45 | /// 46 | /// if (this.DebounceHere()) return; 47 | /// 48 | /// 49 | /// 50 | /// Debounce countdown reference. 51 | /// Usually a caller member owner. 52 | /// It is held weakly. 53 | /// 54 | /// Defaults to if not specified. 55 | /// A compiler-supplied identifier for the call location 56 | /// A compiler-supplied identifier for the call location 57 | public static bool DebounceHere( 58 | this TReference debounceReference, 59 | int? intervalMs = null, 60 | [CallerMemberName] string memberName = "", 61 | [CallerLineNumber] int lineNumber = default) 62 | where TReference : class 63 | { 64 | if (Disabled) 65 | return false; 66 | 67 | var locationKey = $"{memberName}_{lineNumber}"; 68 | 69 | var now = DateTime.UtcNow; 70 | 71 | var objectTimeStamps = _debounceTimeStamps.GetOrAdd(locationKey, valueFactory: _ => new()); 72 | ref var lastStamp = ref objectTimeStamps.GetOrAddRef(debounceReference); 73 | 74 | var interval = intervalMs.HasValue 75 | ? TimeSpan.FromMilliseconds(intervalMs.Value) 76 | : DefaultInterval; 77 | 78 | if (now < lastStamp + interval) 79 | return true; 80 | 81 | lastStamp = now; 82 | return false; 83 | } 84 | 85 | /// 86 | /// Сhecks whether the call of the current line for the 87 | /// has been repeated within the since the last non-repeating call. 88 | /// 89 | /// 90 | /// Usage: 91 | /// 92 | /// if (DebounceMonitor.DebounceHereStatic<SomeStaticClass>()) return; 93 | /// 94 | /// or 95 | /// 96 | /// using static DebounceMonitoring.DebounceMonitor;
97 | /// ...
98 | /// if (DebounceHereStatic<SomeStaticClass>()) return; 99 | ///
100 | ///
101 | /// Debounce countdown reference as a Type. 102 | /// Defaults to if not specified. 103 | /// A compiler-supplied identifier for the call location 104 | /// A compiler-supplied identifier for the call location 105 | public static bool DebounceHereStatic( 106 | int? intervalMs = null, 107 | [CallerMemberName] string memberName = "", 108 | [CallerLineNumber] int lineNumber = default) 109 | where TReferenceType : class => 110 | DebounceHereStatic(typeof(TReferenceType), intervalMs, memberName, lineNumber); 111 | 112 | /// 113 | /// Сhecks whether the call of the current line for the 114 | /// has been repeated within the since the last non-repeating call. 115 | /// 116 | /// 117 | /// Usage: 118 | /// 119 | /// if (DebounceMonitor.DebounceHereStatic(typeof(SomeStaticClass))) return; 120 | /// 121 | /// or 122 | /// 123 | /// using static DebounceMonitoring.DebounceMonitor;
124 | /// ...
125 | /// if (DebounceHereStatic(typeof(SomeStaticClass))) return; 126 | ///
127 | ///
128 | /// Debounce countdown reference. 129 | /// Defaults to if not specified. 130 | /// A compiler-supplied identifier for the call location 131 | /// A compiler-supplied identifier for the call location 132 | public static bool DebounceHereStatic( 133 | Type debounceReference, 134 | int? intervalMs = null, 135 | [CallerMemberName] string memberName = "", 136 | [CallerLineNumber] int lineNumber = default) => 137 | DebounceHere(debounceReference, intervalMs, memberName, lineNumber); 138 | } 139 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Build results 17 | [Dd]ebug/ 18 | [Dd]ebugPublic/ 19 | [Rr]elease/ 20 | [Rr]eleases/ 21 | x64/ 22 | x86/ 23 | [Aa][Rr][Mm]/ 24 | [Aa][Rr][Mm]64/ 25 | bld/ 26 | [Bb]in/ 27 | [Oo]bj/ 28 | [Ll]og/ 29 | 30 | # Visual Studio 2015/2017 cache/options directory 31 | .vs/ 32 | # Uncomment if you have tasks that create the project's static files in wwwroot 33 | #wwwroot/ 34 | 35 | # Visual Studio 2017 auto generated files 36 | Generated\ Files/ 37 | 38 | # MSTest test Results 39 | [Tt]est[Rr]esult*/ 40 | [Bb]uild[Ll]og.* 41 | 42 | # NUNIT 43 | *.VisualState.xml 44 | TestResult.xml 45 | 46 | # Build Results of an ATL Project 47 | [Dd]ebugPS/ 48 | [Rr]eleasePS/ 49 | dlldata.c 50 | 51 | # Benchmark Results 52 | BenchmarkDotNet.Artifacts/ 53 | 54 | # .NET Core 55 | project.lock.json 56 | project.fragment.lock.json 57 | artifacts/ 58 | 59 | # StyleCop 60 | StyleCopReport.xml 61 | 62 | # Files built by Visual Studio 63 | *_i.c 64 | *_p.c 65 | *_h.h 66 | *.ilk 67 | *.meta 68 | *.obj 69 | *.iobj 70 | *.pch 71 | *.pdb 72 | *.ipdb 73 | *.pgc 74 | *.pgd 75 | *.rsp 76 | *.sbr 77 | *.tlb 78 | *.tli 79 | *.tlh 80 | *.tmp 81 | *.tmp_proj 82 | *_wpftmp.csproj 83 | *.log 84 | *.vspscc 85 | *.vssscc 86 | .builds 87 | *.pidb 88 | *.svclog 89 | *.scc 90 | 91 | # Chutzpah Test files 92 | _Chutzpah* 93 | 94 | # Visual C++ cache files 95 | ipch/ 96 | *.aps 97 | *.ncb 98 | *.opendb 99 | *.opensdf 100 | *.sdf 101 | *.cachefile 102 | *.VC.db 103 | *.VC.VC.opendb 104 | 105 | # Visual Studio profiler 106 | *.psess 107 | *.vsp 108 | *.vspx 109 | *.sap 110 | 111 | # Visual Studio Trace Files 112 | *.e2e 113 | 114 | # TFS 2012 Local Workspace 115 | $tf/ 116 | 117 | # Guidance Automation Toolkit 118 | *.gpState 119 | 120 | # ReSharper is a .NET coding add-in 121 | _ReSharper*/ 122 | *.[Rr]e[Ss]harper 123 | *.DotSettings.user 124 | 125 | # JustCode is a .NET coding add-in 126 | .JustCode 127 | 128 | # TeamCity is a build add-in 129 | _TeamCity* 130 | 131 | # DotCover is a Code Coverage Tool 132 | *.dotCover 133 | 134 | # AxoCover is a Code Coverage Tool 135 | .axoCover/* 136 | !.axoCover/settings.json 137 | 138 | # Visual Studio code coverage results 139 | *.coverage 140 | *.coveragexml 141 | 142 | # NCrunch 143 | _NCrunch_* 144 | .*crunch*.local.xml 145 | nCrunchTemp_* 146 | 147 | # MightyMoose 148 | *.mm.* 149 | AutoTest.Net/ 150 | 151 | # Web workbench (sass) 152 | .sass-cache/ 153 | 154 | # Installshield output folder 155 | [Ee]xpress/ 156 | 157 | # DocProject is a documentation generator add-in 158 | DocProject/buildhelp/ 159 | DocProject/Help/*.HxT 160 | DocProject/Help/*.HxC 161 | DocProject/Help/*.hhc 162 | DocProject/Help/*.hhk 163 | DocProject/Help/*.hhp 164 | DocProject/Help/Html2 165 | DocProject/Help/html 166 | 167 | # Click-Once directory 168 | publish/ 169 | 170 | # Publish Web Output 171 | *.[Pp]ublish.xml 172 | *.azurePubxml 173 | # Note: Comment the next line if you want to checkin your web deploy settings, 174 | # but database connection strings (with potential passwords) will be unencrypted 175 | *.pubxml 176 | *.publishproj 177 | 178 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 179 | # checkin your Azure Web App publish settings, but sensitive information contained 180 | # in these scripts will be unencrypted 181 | PublishScripts/ 182 | 183 | # NuGet Packages 184 | *.nupkg 185 | # The packages folder can be ignored because of Package Restore 186 | **/[Pp]ackages/* 187 | # except build/, which is used as an MSBuild target. 188 | !**/[Pp]ackages/build/ 189 | # Uncomment if necessary however generally it will be regenerated when needed 190 | #!**/[Pp]ackages/repositories.config 191 | # NuGet v3's project.json files produces more ignorable files 192 | *.nuget.props 193 | *.nuget.targets 194 | 195 | # Microsoft Azure Build Output 196 | csx/ 197 | *.build.csdef 198 | 199 | # Microsoft Azure Emulator 200 | ecf/ 201 | rcf/ 202 | 203 | # Windows Store app package directories and files 204 | AppPackages/ 205 | BundleArtifacts/ 206 | Package.StoreAssociation.xml 207 | _pkginfo.txt 208 | *.appx 209 | 210 | # Visual Studio cache files 211 | # files ending in .cache can be ignored 212 | *.[Cc]ache 213 | # but keep track of directories ending in .cache 214 | !?*.[Cc]ache/ 215 | 216 | # Others 217 | ClientBin/ 218 | ~$* 219 | *~ 220 | *.dbmdl 221 | *.dbproj.schemaview 222 | *.jfm 223 | *.pfx 224 | *.publishsettings 225 | orleans.codegen.cs 226 | 227 | # Including strong name files can present a security risk 228 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 229 | #*.snk 230 | 231 | # Since there are multiple workflows, uncomment next line to ignore bower_components 232 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 233 | #bower_components/ 234 | 235 | # RIA/Silverlight projects 236 | Generated_Code/ 237 | 238 | # Backup & report files from converting an old project file 239 | # to a newer Visual Studio version. Backup files are not needed, 240 | # because we have git ;-) 241 | _UpgradeReport_Files/ 242 | Backup*/ 243 | UpgradeLog*.XML 244 | UpgradeLog*.htm 245 | ServiceFabricBackup/ 246 | *.rptproj.bak 247 | 248 | # SQL Server files 249 | *.mdf 250 | *.ldf 251 | *.ndf 252 | 253 | # Business Intelligence projects 254 | *.rdl.data 255 | *.bim.layout 256 | *.bim_*.settings 257 | *.rptproj.rsuser 258 | *- Backup*.rdl 259 | 260 | # Microsoft Fakes 261 | FakesAssemblies/ 262 | 263 | # GhostDoc plugin setting file 264 | *.GhostDoc.xml 265 | 266 | # Node.js Tools for Visual Studio 267 | .ntvs_analysis.dat 268 | node_modules/ 269 | 270 | # Visual Studio 6 build log 271 | *.plg 272 | 273 | # Visual Studio 6 workspace options file 274 | *.opt 275 | 276 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 277 | *.vbw 278 | 279 | # Visual Studio LightSwitch build output 280 | **/*.HTMLClient/GeneratedArtifacts 281 | **/*.DesktopClient/GeneratedArtifacts 282 | **/*.DesktopClient/ModelManifest.xml 283 | **/*.Server/GeneratedArtifacts 284 | **/*.Server/ModelManifest.xml 285 | _Pvt_Extensions 286 | 287 | # Paket dependency manager 288 | .paket/paket.exe 289 | paket-files/ 290 | 291 | # FAKE - F# Make 292 | .fake/ 293 | 294 | # JetBrains Rider 295 | .idea/ 296 | *.sln.iml 297 | 298 | # CodeRush personal settings 299 | .cr/personal 300 | 301 | # Python Tools for Visual Studio (PTVS) 302 | __pycache__/ 303 | *.pyc 304 | 305 | # Cake - Uncomment if you are using it 306 | # tools/** 307 | # !tools/packages.config 308 | 309 | # Tabs Studio 310 | *.tss 311 | 312 | # Telerik's JustMock configuration file 313 | *.jmconfig 314 | 315 | # BizTalk build output 316 | *.btp.cs 317 | *.btm.cs 318 | *.odx.cs 319 | *.xsd.cs 320 | 321 | # OpenCover UI analysis results 322 | OpenCover/ 323 | 324 | # Azure Stream Analytics local run output 325 | ASALocalRun/ 326 | 327 | # MSBuild Binary and Structured Log 328 | *.binlog 329 | 330 | # NVidia Nsight GPU debugger configuration file 331 | *.nvuser 332 | 333 | # MFractors (Xamarin productivity tool) working folder 334 | .mfractor/ 335 | 336 | # Local History for Visual Studio 337 | .localhistory/ 338 | 339 | # BeatPulse healthcheck temp database 340 | healthchecksdb --------------------------------------------------------------------------------