OneThreadSynchronizationContext.cs 1.1 KB

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