Created
June 3, 2013 09:10
-
-
Save mattbenic/5697016 to your computer and use it in GitHub Desktop.
A Unity3D coroutine wrapper for simple thread jobs.
This can be added to any utility class, and then passed a thread function (run on the worker thread, be sure to make any shared variable access threadsafe) and a callback called when the thread is done (run on the main thread, no locking needed).
This file contains 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
/// <summary> | |
/// A coroutine used to run a function on once-off thread | |
/// Note that the thread function is responsible for ending itself, | |
/// the coroutine makes no effort to explicitly end the thread. | |
/// </summary> | |
/// <typeparam name="T">Type of the parameter passed to the thread function</typeparam> | |
/// <param name="threadFunc">The thread function</param> | |
/// <param name="doneFunc">Function called when the thread has completed it's work and is no longer alive.</param> | |
/// <param name="param">Parameter passed to the thread function</param> | |
/// <returns>An enumerator</returns> | |
public static IEnumerator ThreadFuncCoroutine<T>( | |
Action<T> threadFunc, | |
Action<T> doneFunc, | |
T param) where T : class | |
{ | |
// Queue the threadfunc on the thread pool | |
// (wrap the user function in one that casts and we can check completion of) | |
bool threadBusy = true; | |
ThreadPool.QueueUserWorkItem( | |
(object obj) => | |
{ | |
threadFunc(param as T); | |
threadBusy = false; | |
}, | |
param); | |
// Wait for the thread to complete | |
do | |
{ | |
// As long as the thread is still running, nothing to do | |
yield return null; | |
} while (threadBusy); | |
// Notify that the thread is done | |
if (null != doneFunc) doneFunc(param); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment