Throttle.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Windows.Forms;
  4. namespace FastReport.Utils
  5. {
  6. internal static class Throttle
  7. {
  8. private static readonly Dictionary<Action, Timer> timers = new Dictionary<Action, Timer>();
  9. private static int suppressCount = 0;
  10. public static void Execute(Action action, int interval = 50)
  11. {
  12. #if (WPF || AVALONIA)
  13. // in WinForms, this may lead to exception (case: close designer and press "Yes" to save file => NRE)
  14. if (timers.ContainsKey(action))
  15. {
  16. var timer = timers[action];
  17. timer.Stop();
  18. timer.Start();
  19. suppressCount++;
  20. }
  21. else
  22. {
  23. var timer = new Timer() { Interval = interval };
  24. timer.Tick += (s, e) =>
  25. {
  26. timer.Dispose();
  27. timers.Remove(action);
  28. if (action.Target is Control control && control.IsDisposed)
  29. return;
  30. action();
  31. };
  32. timers.Add(action, timer);
  33. timer.Start();
  34. }
  35. #else
  36. action();
  37. #endif
  38. }
  39. }
  40. }