How can I check if the thread I'm on is the Unity thread?
I tried capturing the threadId at constructor time, but somewhere along the lifetime of the program, the threadId moves.
In my project, some secondary thread processes need access to a newly created object.
I use the producer-consumer pattern so they can be created on the Unity thread.
An object factory queues a request and on Update()
the objects I requested are instantiated on the correct thread. Between Queued and Instantiated the factory method waits for an ObjectCreated event with an AutoResetEvent.
Now sometimes this factory will be called from the main thread and the AutoResetEvent will block its own thread. I also tried it the dirty way with
// First try on this thread
try
{
return action();
}
catch (ArgumentException ex)
{
Debug.Log("Tried on same thread, but failed. "+ex.Message);
}
PushToQueueAndWait(action);
But when unity throws the exception, caught or not, the program halts.
If I could check whether I'm on the correct thread, I could switch between queueing and just executing.
System.Threading.Thread.CurrentThread.ManagedThreadId
works for me and doesn't change insofar as my testing goes. Also, running threaded code in the Unity Editor's preview mode can result in unexpected behavior. – Gwenni