Skip to content

Instantly share code, notes, and snippets.

@neuecc
Created June 3, 2014 06:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neuecc/904daef01bb1891ca8cb to your computer and use it in GitHub Desktop.
Save neuecc/904daef01bb1891ca8cb to your computer and use it in GitHub Desktop.
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