Issue of unavailable thread context for main-thread-only unity functionalities when called from Namama Socket.ReceiveLoop() async events

Disclaimer: I asked this question on Nakama’s gitter channel and it already have a valid answer, but I’m posting it here just in case other developers find this helpful.

Due to the fact that Socket.ReceiveLoop() is an async func, all the event handlers subscribed to socket events are handled in async context (correct me if I’m mistaken, please). That really limits the functionality in Unity, because now I cannot have a handler to, for example, set a component enabled property to true/false, because Unity mandates to do such a thing on the main thread and throws error if it’s done in a normal (not async) handler subscribed to socket events.
what is the cleanest, most elegant way to bypass such limitations??

The current answer by @novabyte:

You can use the synchronization context from the Unity main thread when you need to do it:

https://github.com/heroiclabs/nakama-unity/blob/master/Assets/Nakama/Snippets/NakamaManager.cs#L108

Alternatively you can use a dispatch queue to move messages from the socket thread onto the Unity main thread. Either pattern works.

update

I simply ended up using the second approach. I found a great repository on GitHub named UnityMainThreadDispatcher and all I have to do now inside my handler subscribed to the async event of Socket:

UnityMainThreadDispatcher.Instance().Enqueue(() => 
{
   //some code that needs to be run on unity's main thread 
});
1 Like

These are the recommended approaches we suggest to manage execution of Unity APIs on the engine’s main thread. It may seem like additional work to incorporate a library like the UnityMainThreadDispatcher one but it gives you fine grained control which is very useful for performance critical code.

1 Like