Program.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System;
  2. using System.Threading;
  3. using ETModel;
  4. namespace Example2_1
  5. {
  6. internal class Program
  7. {
  8. private static int loopCount = 0;
  9. private static void Main()
  10. {
  11. OneThreadSynchronizationContext _ = OneThreadSynchronizationContext.Instance;
  12. WaitTimeAsync(5000, WaitTimeFinishCallback);
  13. while (true)
  14. {
  15. OneThreadSynchronizationContext.Instance.Update();
  16. Thread.Sleep(1);
  17. ++loopCount;
  18. if (loopCount % 10000 == 0)
  19. {
  20. Console.WriteLine($"loop count: {loopCount}");
  21. }
  22. }
  23. }
  24. private static void WaitTimeAsync(int waitTime, Action action)
  25. {
  26. Thread thread = new Thread(()=>WaitTime(waitTime, action));
  27. thread.Start();
  28. }
  29. private static void WaitTimeFinishCallback()
  30. {
  31. Console.WriteLine($"WaitTimeAsync finsih loopCount的值是: {loopCount}");
  32. WaitTimeAsync(4000, WaitTimeFinishCallback3);
  33. }
  34. private static void WaitTimeFinishCallback3()
  35. {
  36. Console.WriteLine($"WaitTimeAsync finsih loopCount的值是: {loopCount}");
  37. WaitTimeAsync(3000, WaitTimeFinishCallback2);
  38. }
  39. private static void WaitTimeFinishCallback2()
  40. {
  41. Console.WriteLine($"WaitTimeAsync finsih loopCount的值是: {loopCount}");
  42. }
  43. /// <summary>
  44. /// 在另外的线程等待
  45. /// </summary>
  46. private static void WaitTime(int waitTime, Action action)
  47. {
  48. Thread.Sleep(waitTime);
  49. // 将action扔回主线程执行
  50. OneThreadSynchronizationContext.Instance.Post(o=>action(), null);
  51. }
  52. }
  53. }