OneThreadSynchronizationContext.cs 693 B

1234567891011121314151617181920212223242526272829303132333435
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Threading;
  4. namespace ETModel
  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 (true)
  17. {
  18. Action a;
  19. if (!this.queue.TryDequeue(out a))
  20. {
  21. return;
  22. }
  23. a();
  24. }
  25. }
  26. public override void Post(SendOrPostCallback callback, object state)
  27. {
  28. this.Add(() => { callback(state); });
  29. }
  30. }
  31. }