如何检查我所在的线程是否为 Unity 线程?
我尝试在构造函数时捕获 threadId,但在程序生命周期的某个时间点,threadId 发生了变化。
在我的项目中,一些辅助线程进程需要访问一个新创建的对象。
我使用生产者-消费者模式,因此它们可以在 Unity 线程上创建。
对象工厂对请求进行排队,然后在 Update()
上,我请求的对象在正确的线程上实例化。在 Queued 和 Instantiated 之间,工厂方法等待带有 AutoResetEvent 的 ObjectCreated 事件。
现在有时会从主线程调用这个工厂,而 AutoResetEvent 会阻塞它自己的线程。 我也用
以肮脏的方式尝试了它// First try on this thread
try
{
return action();
}
catch (ArgumentException ex)
{
Debug.Log("Tried on same thread, but failed. "+ex.Message);
}
PushToQueueAndWait(action);
但是当 unity 抛出异常时,无论是否被捕获,程序都会停止。
如果我可以检查我是否在正确的线程上,我可以在排队和执行之间切换。
最佳答案
我通过捕获整个线程然后像这样等于它来解决它:
public void Start(){
mainThread = System.Threading.Thread.CurrentThread;
}
bool isMainThread(){
return mainThread.Equals(System.Threading.Thread.CurrentThread);
}
相关:http://answers.unity3d.com/questions/62631/i-wonder-about-thread-id-plz-answer-me.html
关于c# - 看看我是否在统一线程上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26452609/