Hi
Am I correct that the callback method from a System.Timers.Timer cannot be used as is in Unity because the callback does not execute in the Main thread?
If so, is there a good workaround?
Before anyone suggest I DON’T use System.Timers.Timer this is for a non MonoBehaviour server Class, part of a Unity ad playing application I am building.
System.Timers.Timer seems to be the most precise solution based on the documentation I have read.
If you’re on a different thread, and you need to get back to the main thread, you need to hook back into it.
A common simple way of doing this is having a singleton MonoBehaviour that stores a System.Action delegate, and every update it sees if it exists and calls it.
Something like this:
public class MainThreadHook : MonoBehaviour
{
#region Singleton
//implement your singleton in some manner
private static MainThreadHook _instance;
void Awake()
{
_instance = this;
}
#endregion
#region Fields
private System.Action _callback;
#endregion
#region Methods
void Update()
{
var a = _callback;
_callback = null;
if(a != null)
{
a();
}
}
public static void Invoke(System.Action a)
{
_callback += a;
}
#endregion
}
There are various other techniques.
Also that’s mostly psuedo-code, I don’t fully implement the singleton, nor is it thread safe. You need to beef it up, I just slapped it together here in the browser as a guide.
Hey, thanks! I just came across another possible solution.
Would appreciate your thoughts on possible pros, cons vs your solution.
UnityThread’ >
http://stackoverflow.com/questions/41330771/use-unity-api-from-another-thread-or-call-a-function-in-the-main-thread/41333540#41333540
PS, I DID finally get the solution for the TCP server in Unity on another old thread here in the forums, but very much appreciate your feedback! TCP server in Unity - Unity Engine - Unity Discussions
I mean honestly, that is just what I wrote with some extra bells and whistles added and a lock to make it more thread safe, and the singleton fully implemented (I just slap dashed with some notation).
So yeah, it should work.