Threading Syntax

MEC Threaded uses MEC. MEC Free is included in the project, but if you have MEC Pro or any other plugin from Trinary Software just import them over the top. It may also be possible that there is a more current version of MEC Free in the asset store, which is also ok to import over the top of the one included here.

The interface for MEC Threaded is very simple: You switch to another thread using a yield return statement within a coroutine. You can then end the coroutine or switch back to the main thread using another yield return statement.

yield return Threading.SwitchToExternalThread();
// Do stuff and then optionally use the following line to switch back
yield return Threading.SwitchBackToGUIThread;

Most of the time it’s best to just run your threads at the default (normal) priority. Thread priority makes the thread take up more or less of the “attention” of the CPU. If you want to run at a different priority you can pass it into the SwitchTo function.

yield return Threading.SwitchToExternalThread(ThreadPriority.Low);

Normally you want to use the thread pool because it’s more efficient, however if you expect your thread to take longer than one frame to execute then it’s better to use a dedicated external thread. Also if you want to use Threading.Sleep to sleep for a long time inside your thread it’s best to use a dedicated thread for that.

yield return Threading.SwitchToDedicatedExternalThread();
Threading.Sleep(number);

Threading.Sleep takes a “number of seconds” float. It’s ok to use a pooled thread to sleep for short periods of time (if your thread is watching a network stream for example), just be sure to yield to other tasks between sleeps in case there’s another thread waiting:

Threading.Sleep(0.016f);
yield return Threading.YieldToOtherTasksOnThisThread;