OneThreadSynchronizationContext.cs 905 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using System;
  2. using System.Threading;
  3. namespace Model
  4. {
  5. public class OneThreadSynchronizationContext : SynchronizationContext
  6. {
  7. // 线程同步队列,发送接收socket回调都放到该队列,由poll线程统一执行
  8. private EQueue<Action> queue = new EQueue<Action>();
  9. private EQueue<Action> localQueue = new EQueue<Action>();
  10. private readonly object lockObject = new object();
  11. private void Add(Action action)
  12. {
  13. lock (lockObject)
  14. {
  15. this.queue.Enqueue(action);
  16. }
  17. }
  18. public void Update()
  19. {
  20. lock (lockObject)
  21. {
  22. if (this.queue.Count == 0)
  23. {
  24. return;
  25. }
  26. localQueue = queue;
  27. queue = new EQueue<Action>();
  28. }
  29. while (this.localQueue.Count > 0)
  30. {
  31. Action a = this.localQueue.Dequeue();
  32. a();
  33. }
  34. }
  35. public override void Post(SendOrPostCallback callback, object state)
  36. {
  37. this.Add(() => { callback(state); });
  38. }
  39. }
  40. }