You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

78 lines
1.7 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4. using CIG.Extensions;
  5. using UnityEngine;
  6. namespace CIG
  7. {
  8. public class AdProviderMonoBehaviour : MonoBehaviour
  9. {
  10. private void Start()
  11. {
  12. this._mainThread = Thread.CurrentThread;
  13. this.InvokeRepeating(new Action(this.InvokeMainThreadQueue), 1f, 1f, true);
  14. }
  15. private void OnDestroy()
  16. {
  17. this.CancelInvoke(new Action(this.InvokeMainThreadQueue));
  18. }
  19. public void InvokeOnMainThread(Action action, float time)
  20. {
  21. if (object.ReferenceEquals(Thread.CurrentThread, this._mainThread))
  22. {
  23. this.Invoke(action, time, false);
  24. }
  25. else
  26. {
  27. this.EnqueueActionOnMainThread(delegate
  28. {
  29. this.Invoke(action, time, false);
  30. });
  31. }
  32. }
  33. private void EnqueueActionOnMainThread(Action action)
  34. {
  35. object updateOnMainThreadActionsLock = this._updateOnMainThreadActionsLock;
  36. lock (updateOnMainThreadActionsLock)
  37. {
  38. this._updateOnMainThreadActions.Enqueue(action);
  39. }
  40. }
  41. private void InvokeMainThreadQueue()
  42. {
  43. if (this._updateOnMainThreadActions.Count > 0)
  44. {
  45. Action action;
  46. do
  47. {
  48. action = null;
  49. object updateOnMainThreadActionsLock = this._updateOnMainThreadActionsLock;
  50. lock (updateOnMainThreadActionsLock)
  51. {
  52. if (this._updateOnMainThreadActions.Count > 0)
  53. {
  54. action = this._updateOnMainThreadActions.Dequeue();
  55. }
  56. }
  57. if (action != null)
  58. {
  59. action();
  60. }
  61. }
  62. while (action != null);
  63. }
  64. }
  65. private Thread _mainThread;
  66. private readonly object _updateOnMainThreadActionsLock = new object();
  67. private readonly Queue<Action> _updateOnMainThreadActions = new Queue<Action>();
  68. }
  69. }