线程结束时在主线程上回调

Callback on main thread when a thread finishes

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

您可以使用async/await..

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

还有一个好处,你可以用 try-catch 块包围它,并以一种聪明的方式捕获你工作中可能发生的异常。

//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
}