Unity c#脚本中调用主线程方法

首先我们要先获取主线程的SynchronizationContext ,在初始化的时候(即从主线程调用时)将当前的context并保存下来。

private static SynchronizationContext mainThreadSyncContext;
public static void Init()
{
    mainThreadSyncContext = SynchronizationContext.Current;
}
1
2
3
4
5
然后在需要的地方使用SynchronizationContext的Post方法调用即可,例如:

pc.Exited += (object sender, EventArgs e) =>
    {
        mainThreadSyncContext.Post(_ =>
        {
            // This code here will run on the main thread
            callBack.Invoke(sender, e);
        }, null);                    
    };  
 

猜你喜欢

转载自blog.csdn.net/qq_21743659/article/details/128529017