gpt4 book ai didi

c# - 如何在不使用 Unity 协程的情况下在主线程上运行函数

转载 作者:太空宇宙 更新时间:2023-11-03 18:27:40 24 4
gpt4 key购买 nike

我看过一些关于使用协程在主线程上运行函数的文章,例如 Thread Ninja :

 IEnumerator StartExamples()
{
//Jump to main thread
yield return Ninja.JumpToUnity;

Destroy(someGameObject); //OK

//Jump back to background thread
yield return Ninja.JumpBack;
}

它对我的代码不起作用,因为我想从套接字监听器跳转到主线程。

 SocketIOClient.Client socket;

IEnumerator StartExamples()
{
socket.On("connect", (fn) =>
{
WriteLine("\r\nConnected event...\r\n");

//Jump to main thread
yield return Ninja.JumpToUnity; //ERROR: couldn't do a yield return

Destroy(someGameObject);

//Jump back to background thread
yield return Ninja.JumpBack; //ERROR: couldn't do a yield return
});
}

那么我们有什么解决方法吗?我希望我能像这样跳转到主线程:

 Dispatcher.BeginInvoke(() =>
{
//Unity API
Destroy(gameObject);
});

最佳答案

根据我的评论,使用 uPromise ;

class Example
{
private Promise BeginSocketConnection()
{
Deferred retPromise = new Deferred();

socket.On("connect", (fn) =>
{
// We're no longer on the main thread ):
// But we can resolve our promise!
retPromise.Resolve();
});

return retPromise;
}

private void SocketConnectedSuccessfully()
{
// Executing on main thread
}

private void Start()
{
// We start in the main thread
BeginSocketConnection().Done(x =>
{
SocketConnectedSuccessfully();
});
}
}

这不允许您在同一个代码块内的线程之间跳转,但通过使用回调系统,您可以提醒主线程执行一个操作,而无需启动杂乱的协程并在各处产生。更易于查看和维护。

关于c# - 如何在不使用 Unity 协程的情况下在主线程上运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30297792/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com