OneThreadSynchronizationContext.cs 878 B

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