ThreadSyncContext.cs 901 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Concurrent;
  4. using System.Threading;
  5. namespace YooAsset
  6. {
  7. /// <summary>
  8. /// 同步其它线程里的回调到主线程里
  9. /// 注意:Unity3D中需要设置Scripting Runtime Version为.NET4.6
  10. /// </summary>
  11. internal sealed class ThreadSyncContext : SynchronizationContext
  12. {
  13. private readonly ConcurrentQueue<Action> _safeQueue = new ConcurrentQueue<Action>();
  14. /// <summary>
  15. /// 更新同步队列
  16. /// </summary>
  17. public void Update()
  18. {
  19. while (true)
  20. {
  21. if (_safeQueue.TryDequeue(out Action action) == false)
  22. return;
  23. action.Invoke();
  24. }
  25. }
  26. /// <summary>
  27. /// 向同步队列里投递一个回调方法
  28. /// </summary>
  29. public override void Post(SendOrPostCallback callback, object state)
  30. {
  31. Action action = new Action(() => { callback(state); });
  32. _safeQueue.Enqueue(action);
  33. }
  34. }
  35. }