Create a gist now

Instantly share code, notes, and snippets.

Unity: Creating a Thread and Making Callback Called by UI Thread
delegate void JobResultHandler(bool result);
public static void DoJobAsync (string someParameter, JobResultHandler jobResultHandler = null)
//If callback is null; we do not need unity adapter, otherwise we need to create it in ui thread.
ThreadAdapter adapter = jobResultHandler == null ? null : CreateUnityAdapter ();
System.Threading.ThreadPool.QueueUserWorkItem (
//jobResultHandler is a function reference; which will be called by UIThread with result data
new System.Threading.WaitCallback (ExecuteJob),new object[] { someParameter,adapter,jobResultHandler});
private static void ExecuteJob (object state)
object[] array = state as object[];
string someParameter = (string)array [0];
ThreadAdapter adapter =array [1] as ThreadAdapter;
JobResultHandler callback =array [2] as JobResultHandler;
//... time consuming job is performed here...
bool result = ComplexJob (someParameter);
//if adapter is not null; callback is also not null.
if (adapter != null) {
adapter.ExecuteOnUi (delegate {
callback (result);
/// <summary>
/// Must be called from an ui thread
/// </summary>
/// <returns>The unity adapter.</returns>
internal static ThreadAdapter CreateUnityAdapter ()
GameObject gameObject = new GameObject ();
return gameObject.AddComponent<ThreadAdapter> ();
internal class ThreadAdapter : MonoBehaviour {
private volatile bool waitCall = true;
public static int x = 0;
//this will hold the reference to delegate which will be
//executed on ui thread
private volatile Action theAction;
public void Awake() {
DontDestroyOnLoad (gameObject); = "ThreadAdapter-" + (x++);
public IEnumerator Start() {
while (waitCall) {
yield return new WaitForSeconds(.05f);
theAction ();
Destroy (gameObject);
public void ExecuteOnUi (Action action)
this.theAction = action;
waitCall = false;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment