0

我有以下代码...

StartCoroutine(GetSuggestions());

IEnumerator GetSuggestions() {
    longExecutionFunction(); // this takes a long time
    yield return null;
}

我如何使用协程来保持主程序流程继续进行?目前当它达到 longExecutionFunction(); 程序停止几秒钟。如果整个程序在此过程中继续工作,我会很高兴。我怎样才能做到这一点?

4

3 回答 3

2

不使用线程,假设你可以修改longExecutionFunction,它看起来像这样:

void longExecutionFunction()
{
    mediumExecutionFunction();
    mediumExecutionFunction();
    while(working)
    {
        mediumExecutionFunction();
    }
}

您可以将其修改为:

IEnumerator longExecutionFunction()
{
    mediumExecutionFunction();
    yield return null;
    mediumExecutionFunction();
    yield return null;
    while(working)
    {
        mediumExecutionFunction();
        yield return null;
    }
}

然后修改调用代码如下:

StartCoroutine(GetSuggestions());

IEnumerator GetSuggestions() {
    yield return longExecutionFunction();
    //all done!
}

然后,每次更新都会做一件“中等长度的事情”,从而防止游戏挂起。您是否可以以及如何分解内部的工作longExecutionFunction取决于您在其中的代码。

于 2013-04-12T06:14:54.167 回答
0

You would need to start longExecutionFunction in another thread. You may want to look at this article to read about threading: http://msdn.microsoft.com/en-us/library/system.threading.thread.aspx

Code Example:

var thread = new System.Threading.Thread(new System.Threading.ThreadStart(() => {
    longExecutionFunction();
}));
thread.Start();

If you aren't familiar with threads you should read up on them before using them. :)

于 2013-04-11T16:46:22.703 回答
0

您应该将线程与协程结合使用。

StartCoroutine(MyCoroutine());

[...]

IEnumerator MyCoroutine()
{
    Thread thread = new Thread(() =>
    {
        longExecutionFunction();
    });

    thread.Start();

    while (thread.IsAlive) yield return 0;

    // ... Use data here
}

但是,您不能在 中使用任何统一对象或方法longExecutionFunction,因为统一不是线程安全的。longExecutionFunction因此,当方法返回时,您需要计算内部的所有数据并初始化统一对象。

于 2013-04-11T17:58:39.333 回答