Created
June 3, 2014 06:54
-
-
Save neuecc/904daef01bb1891ca8cb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MonoBehaviourSynchronizationContext : SynchronizationContext | |
{ | |
object gate = new object(); | |
Queue<KeyValuePair<SendOrPostCallback, object>> actionQueue = new Queue<KeyValuePair<SendOrPostCallback, object>>(); | |
public MonoBehaviourSynchronizationContext(MonoBehaviour monoBehaviour) | |
{ | |
monoBehaviour.StartCoroutine(Run()); | |
} | |
IEnumerator Run() | |
{ | |
while (true) | |
{ | |
lock (gate) | |
{ | |
while (actionQueue.Count != 0) | |
{ | |
var action = actionQueue.Dequeue(); | |
try | |
{ | |
action.Key(action.Value); | |
} | |
catch (Exception ex) | |
{ | |
Debug.LogException(ex); | |
} | |
} | |
} | |
yield return null; | |
} | |
} | |
public override void Send(SendOrPostCallback d, object state) | |
{ | |
lock (gate) | |
{ | |
actionQueue.Enqueue(new KeyValuePair<SendOrPostCallback, object>(d, state)); | |
} | |
} | |
public override void Post(SendOrPostCallback d, object state) | |
{ | |
lock (gate) | |
{ | |
actionQueue.Enqueue(new KeyValuePair<SendOrPostCallback, object>(d, state)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment