I have some trouble with threading in my application. I have a multi-threaded client/server application. I’m also using C# MonoDevelop for Unity3d. Not sure if it makes any difference for the answer. I’ll try to explain where my problem is:
Unity works on a single thread. So if i want to instantiate an object which uses the abstract class ScriptableObject from unity, then this must be done on the main thread on which Unity runs.
But my server socket spawns a thread for every connected client, so that incoming data can be processed async. The received data is processed in the OnDataReceived() method (which runs on its own thread)
The problem here is, is that i can’t create an instance of a Player object inside the OnDataReceived() thread. Because my Player object inherits from ScriptableObject. Which means this object should be created on the main Unity thread.
But i have no idea how to do that… Is there a way to switch back to the main thread, so i can still create a Player object in the OnDataReceived() method?
.NET already has a concept of a
SynchronizationContext, most often used for UI apps where thread affinity is required to invoke operations on UI controls (e.g. in WPF or WinForms). However, even outside a UI app, you can reuse these concepts for a general purpose thread-affinitized work queue.This sample shows how to use the WPF
DispatcherSynchronizationContext(fromWindowsBase.dll) in a simple console application, together with the .NET 4.0 task classes (TaskScheduler/Task) to invoke actions originating on child threads back on the main program thread.Sample output: