简体   繁体   English

如何在 C# 中等待 IEnumerator function 的完全执行?

[英]How to wait for the complete execution of a IEnumerator function in C#?

I want to get the result of a webrequest in another function but unfortunately the variable of the webrequest stays empty, because the webrequest isn't already xecuted when I call the variable.我想在另一个 function 中获得 webrequest 的结果,但不幸的是 webrequest 的变量保持为空,因为当我调用变量时 webrequest 尚未执行。 I call the OpenFile Function which calls the GetText one:我将调用 GetText 的 OpenFile Function 称为:

private string[] m_fileContent;

public void OpenFile(string filePath)
    {
        StartCoroutine(GetText());
        Console.Log(m_fileContent);// is empty
    }

IEnumerator GetText()
    {
        UnityWebRequest www = UnityWebRequest.Get("http://...");
        yield return www.SendWebRequest();

        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
            m_fileContent = www.downloadHandler.text.Split('\n');
            Debug.Log("here" + m_fileContent);//data printed ok

        }
    }

So the GetText function prints the text but in the OpenFile function the variable m_fileContent is empty.因此 GetText function 打印文本,但在 OpenFile function 中,变量 m_fileContent 为空。

Any ideas how to solve this?任何想法如何解决这个问题?

Thank you!谢谢!

The issue问题

The line线

Console.Log(m_fileContent);

is reached immediately and doesn't wait until the Coroutine finished.立即到达并且不等到协程完成。

Solution解决方案

Use an Action<string[]> and pass in a callback like eg使用Action<string[]>并传入回调,例如

public void OpenFile(string filePath, Action<string[]> onTextResult)
{
    // pass in a callback that handles the result string
    StartCoroutine(GetText(onTextResult));
}

IEnumerator GetText(Action<string[]> onResult)
{
    UnityWebRequest www = UnityWebRequest.Get("http://...");
    yield return www.SendWebRequest();

    if (www.isNetworkError || www.isHttpError)
    {
        Debug.Log(www.error);
    }
    else
    {
        var fileContent = www.downloadHandler.text.Split('\n');

        // Invoke the passed action and pass in the file content 
        onResult?.Invoke(fileContent);
    }
}

And then call it like然后像这样称呼它

// Either as lambda expression
OpenFile("some/file/path", fileContent => {
    Console.Log(fileContent);
});

// or using a method
OpenFile("some/file/path", OnFileResult);

...

private void OnFileResult(string[] fileContent)
{
    Console.Log(fileContent);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM