OneThreadSynchronizationContext.cs 694 B

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