【问题标题】:Callback on main thread when a thread finishes线程完成时回调主线程
【发布时间】:2015-08-27 02:42:55
【问题描述】:

我需要在工作线程完成时通知主线程。当我完成委托并在另一个线程上执行它时,它会在该线程上执行,这不是我想要的。由于我有一些限制,我也无法检查它是否完成(Unity 编辑器中的“更新”不是每帧都调用)。我还有其他选择吗?

【问题讨论】:

    标签: c# multithreading unity3d callback


    【解决方案1】:

    你可以使用 async/await..

    async void MyFunc()
    {
        await Task.Run(() => { /* your work in thread */ });
        //Your work is finished at this point
    }
    

    另外,您可以用 try-catch 块包围它,并以智能的方式捕获您工作中可能发生的异常。

    【讨论】:

    • 这可能是最好的解决方案,但 Unity 似乎不支持它。无论如何,将其标记为正确,因为它很好,我找到了一个不同的黑客解决方案:通过订阅 UnityEditor.EditorApplication.update 修复更新问题,它确实在每一帧都被调用。
    • async void 很危险,最好使用async Task 作为返回类型
    • 这在当前版本的 Unity 5.4.x 中不起作用(由于显而易见的原因,在发布答案时它也没有返回),因为使用的 Mono 运行时相当于 .NET 3.5 和 C# 版本是 3.0,一些功能从 4.0 开始可用。不过,Unity 正在慢慢适应更新的 Mono 运行时和 C# 版本...
    【解决方案2】:
    //This is a helper coroutine
    IEnumerable RunOffMainThread(Action toRun, Action callback) {
      bool done = false;
      new Thread(()=>{
        toRun();
        done = true;
      }).Start();
      while (!done)
        yield return null;
      callback();
    }
    
    //This is the method you call to start it
    void DoSomethingOffMainThread() {
      StartCoroutine(RunOffMainThread(ToRun, OnFinished));
    }
    
    //This is the method that does the work
    void ToRun() {
      //Do something slow here
    }
    
    //This is the method that's called when finished
    void OnFinished() {
       //off main thread code finished, back on main thread now
    }
    

    【讨论】:

    • 和默认Update一样的问题,unity编辑器不会每帧调用协程:(
    • 我明白了,我没有意识到问题出在编辑器上。
    • 即使对编辑器不起作用,这种用法对播放器来说也是一个爆炸!
    猜你喜欢
    • 2015-04-06
    • 1970-01-01
    • 2016-06-06
    • 2020-09-21
    • 2014-10-05
    • 1970-01-01
    • 2018-02-15
    • 1970-01-01
    • 2016-04-11
    相关资源
    最近更新 更多