【问题标题】:UnityWebRequest constructor block in a ReadToEndAsync callbackReadToEndAsync 回调中的 UnityWebRequest 构造函数块
【发布时间】:2023-04-10 04:24:01
【问题描述】:

我不明白为什么 UnityWebRequest 构造函数没有在此回调中返回。是线程问题吗?

StreamReader streamReader = new StreamReader("C:\\file.txt");

streamReader.ReadToEndAsync().ContinueWith((task) => {
    Debug.Log("read done");

    UnityWebRequest request = new UnityWebRequest();

    Debug.Log("web request created");
});

在 Unity 控制台中,我只看到“读取完成”消息。

【问题讨论】:

  • ContinueWith 可能在后台线程上执行,UnityWebRequest 的构造函数会抛出您在主线程中看不到的异常 => 后台任务静默失败
  • 是的,这绝对是线程问题,但我找到了使用主线程的解决方案,谢谢

标签: c# unity3d asynchronous networking io


【解决方案1】:

终于有人给了我这个解决方案:

StreamReader streamReader = new StreamReader("C:\\file.txt");

async void AsyncRead(StreamReader reader) {
    Debug.Log("in the function");

    Task<String> task = reader.ReadToEndAsync();
    await task;

    Debug.Log("reading done");

    UnityWebRequest unityWebRequest = new UnityWebRequest();

    Debug.Log("web request created");
}

AsyncRead(streamReader);

Debug.Log("async reading started");

UnityWebRequest 构造函数不再阻塞,我在统一控制台中得到了我想要的:

in the function
async reading started

...more later...

reading done
web request created

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-25
    • 2018-01-31
    • 1970-01-01
    相关资源
    最近更新 更多