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:


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