ThreadSynchronizationContext.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Threading;
  4. namespace ET
  5. {
  6. public class ThreadSynchronizationContext : SynchronizationContext
  7. {
  8. public static ThreadSynchronizationContext Instance { get; } = new ThreadSynchronizationContext(Thread.CurrentThread.ManagedThreadId);
  9. private readonly int threadId;
  10. // 线程同步队列,发送接收socket回调都放到该队列,由poll线程统一执行
  11. private readonly ConcurrentQueue<Action> queue = new ConcurrentQueue<Action>();
  12. private Action a;
  13. public ThreadSynchronizationContext(int threadId)
  14. {
  15. this.threadId = threadId;
  16. }
  17. public void Update()
  18. {
  19. while (true)
  20. {
  21. if (!this.queue.TryDequeue(out a))
  22. {
  23. return;
  24. }
  25. try
  26. {
  27. a();
  28. }
  29. catch (Exception e)
  30. {
  31. Log.Error(e);
  32. }
  33. }
  34. }
  35. public override void Post(SendOrPostCallback callback, object state)
  36. {
  37. this.Post(() => callback(state));
  38. }
  39. public void Post(Action action)
  40. {
  41. if (Thread.CurrentThread.ManagedThreadId == this.threadId)
  42. {
  43. try
  44. {
  45. action();
  46. }
  47. catch (Exception e)
  48. {
  49. Log.Error(e);
  50. }
  51. return;
  52. }
  53. this.queue.Enqueue(action);
  54. }
  55. public void PostNext(Action action)
  56. {
  57. this.queue.Enqueue(action);
  58. }
  59. }
  60. }