IWinFormDispatcher.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using System;
  2. using System.Threading;
  3. namespace FastGithub.Windows.Hosting
  4. {
  5. /// <summary>
  6. /// WinForm调度器
  7. /// </summary>
  8. public interface IWinFormDispatcher
  9. {
  10. /// <summary>
  11. /// 获取或设置同步上下文
  12. /// </summary>
  13. SynchronizationContext? SynchronizationContext { get; set; }
  14. /// <summary>
  15. /// 尝试在同步上下文投递执行委托
  16. /// </summary>
  17. /// <param name="action"></param>
  18. /// <returns></returns>
  19. bool TryInvoke(Action action)
  20. {
  21. var context = this.SynchronizationContext;
  22. if (context == null || action == null)
  23. {
  24. return false;
  25. }
  26. context.Post(state => ((Action)state!)(), action);
  27. return false;
  28. }
  29. /// <summary>
  30. /// 在同步上下文投递执行委托
  31. /// </summary>
  32. /// <param name="action"></param>
  33. void Invoke(Action action)
  34. {
  35. var context = this.SynchronizationContext;
  36. if (context == null)
  37. {
  38. throw new InvalidOperationException($"{nameof(SynchronizationContext)} is null");
  39. }
  40. if (action != null)
  41. {
  42. context.Post(state => ((Action)state!)(), action);
  43. }
  44. }
  45. }
  46. }