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.
I solved it by capturing the entire thread and then equalling it like so:
public void Start(){
mainThread = System.Threading.Thread.CurrentThread;
}
bool isMainThread(){
return mainThread.Equals(System.Threading.Thread.CurrentThread);
}
Related: http://answers.unity3d.com/questions/62631/i-wonder-about-thread-id-plz-answer-me.html
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句