Threading
Threading, a light weight thread dispatcher for Unity3D. I’ve found that whenever I needed to do any multi-threading in a Unity3D context I would need to find some mechanism for thread synchronisation to the main-thread. I decided to create this light weight dispatcher library to use and extend going forward. The goal of Threading is to simplify synchronisation between the main and worker threads.
You can also get Threading on the Unity3D Asset Store if you feel like donating and have easy integration with the Unity3D Package Manager.
Rationale
In any game or Unity3D project, having a steady framerate and great performance is an absolute must. Sub-par performance is a project killer when it comes to games. This is why we often want to delegate long running or heavy calculations off to worker threads and might even parallelize them.
The problem however is the fact that the Unity3D API is not thread-safe. This leads to all kinds of synchronisation mechanisms and Threading is a light weight version of one of such mechanisms.
I’ve written small custom versions of synchronisation mechanisms for many project I do and I wanted to have a single source of truth to use in future projects.
Threading is a simple yet limited library, for now. But as I write more projects I can reuse the code and the functionality will grow to be more complete. The main idea is to have a single entry point for synchronisation between the main and worker threads.
DevLog
Well there is not really much to say here since Threading is juse a really simple library.
The thing that might set Threading apart from other Dispatcher based mechanisms you might find on the Unity3D asset store is the feature to be able to synchronize, very easily, between the main and worker threads in Tasks.
I have written many adhoc dispatchers over the years and decided to create this little library to use going forward. Currently it’s based on the static Dispatcher class but I will add more context aware mechanisms in the future. For example; a Dispatcher bound to Scene, or gameobject life-cycle. Or maybe one that implements IDisposable to comply to the scope of the using statement. I’m not sure.
The current Dispatcher will synchronize C# Actions or Tasks to the main-thread in the Update loop. I could add a similar mechanism to synchronize with other stages in the Unity Event loop but for now I’ve not needed it. An example would be to synchronize during the FixedUpdate when you need to do any physics related code.
The most interesting part in writing this little Threading library was to add a custom awaiter for synchronisation from the main-thread to some worker thread. I didn’t know how to do synchronize to a worker thread before but it’s actually pretty easy. Having this available is nice although its just some syntactic sugar around dealing with the UnitySynchronizationContext.
I’ll try to keep this log updated once new features are added to Threading.