OneThreadSynchronizationContext.cs 744 B

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