代码之家  ›  专栏  ›  技术社区  ›  Ludwik

区域描述。SaveCurrent()冻结Unity的更新循环,尽管有新线程

  •  0
  • Ludwik  · 技术社区  · 7 年前

    Debug.Log("create thread");
    m_saveThread = new Thread(() =>
    {
        // Start saving process in another thread.
        Debug.Log("Starting work in thread");
        currentAreaDescription = AreaDescription.SaveCurrent();
        Debug.Log("SaveCurrent completed");
        AreaDescription.Metadata metadata = currentAreaDescription.GetMetadata();
        metadata.m_name = name;
        currentAreaDescription.SaveMetadata(metadata);
    });
    
    Debug.Log("Start thread");
    m_saveThread.Start();
    Debug.Log("thread started");
    

    我的问题是,即使我在一个新线程中运行保存代码,UI仍然被冻结,直到 AreaDescription.SaveCurrent() Update() :

    public void Update()
    {
        Debug.Log("Update!");
        //...
    }
    

    这是摘自 adb logcat -s Unity 在我保存时:

    08-23 15:11:43.746 18474 18518 I Unity   : Update!
    08-23 15:11:43.747 18474 18518 I Unity   : Save confirmed!
    08-23 15:11:43.747 18474 18518 I Unity   : overlay
    08-23 15:11:43.747 18474 18518 I Unity   : create thread
    08-23 15:11:43.748 18474 18518 I Unity   : Start thread
    08-23 15:11:43.753 18474 18518 I Unity   : thread started
    08-23 15:11:43.754 18474 18836 I Unity   : Starting work in thread
    08-23 15:11:44.960 18474 18518 I Unity   : Update!
    08-23 15:11:44.961 18474 18518 I Unity   : Currently saving!
    08-23 15:11:44.964 18474 18836 I Unity   : SaveCurrent completed
    08-23 15:11:44.977 18474 18518 I Unity   : Update!
    

    从时间戳可以看出,对于整个200毫秒 SaveCurrent() 跑, 更新() 没有被呼叫。

    事实上 在后台运行?

    顺便说一句,这段代码几乎直接改编自 Google's own sample repo 我创造了 an issue 关于它,目前没有回应。

    2 回复  |  直到 7 年前
        1
  •  2
  •   Ludwik    7 年前

    在找到 C API function that gets called under the hood 阅读了它的文档,我发现

    事实上,我的场景中还有其他对象在其 Update()

    Tango docs about the Unity function I was using .

        2
  •  0
  •   KYL3R    7 年前

    在引擎盖下, SaveCurrent() 系统Xml。序列化。XmlSerializer msdn ,线程安全。

    但他们用一个 StreamWriter 非静态成员不是线程安全的。

    但是有 TextWriter.Synchronized

    仍然不清楚为什么一个单独的线程会导致统一冻结。我们必须假设Unity等待线程完成/不再阻塞。

    扩展单行为,看看Unity是否停止等待。

    answers.unity3d thread