ThreadSynchronizationContext.cs 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Threading;
  4. namespace ET
  5. {
  6. public class ThreadSynchronizationContext : SynchronizationContext
  7. {
  8. // 线程同步队列,发送接收socket回调都放到该队列,由poll线程统一执行
  9. private readonly ConcurrentQueue<Action> queue = new ConcurrentQueue<Action>();
  10. private Action a;
  11. public void Update()
  12. {
  13. while (true)
  14. {
  15. if (!this.queue.TryDequeue(out a))
  16. {
  17. return;
  18. }
  19. try
  20. {
  21. a();
  22. }
  23. catch (Exception e)
  24. {
  25. Log.Error(e);
  26. }
  27. }
  28. }
  29. public override void Post(SendOrPostCallback callback, object state)
  30. {
  31. this.Post(() => callback(state));
  32. }
  33. public void Post(Action action)
  34. {
  35. this.queue.Enqueue(action);
  36. }
  37. }
  38. }