繁体   English   中英

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

[英]Callback on main thread when a thread finishes

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

您可以使用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
}

暂无
暂无

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

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