【发布时间】:2015-08-27 02:42:55
【问题描述】:
我需要在工作线程完成时通知主线程。当我完成委托并在另一个线程上执行它时,它会在该线程上执行,这不是我想要的。由于我有一些限制,我也无法检查它是否完成(Unity 编辑器中的“更新”不是每帧都调用)。我还有其他选择吗?
【问题讨论】:
标签: c# multithreading unity3d callback
我需要在工作线程完成时通知主线程。当我完成委托并在另一个线程上执行它时,它会在该线程上执行,这不是我想要的。由于我有一些限制,我也无法检查它是否完成(Unity 编辑器中的“更新”不是每帧都调用)。我还有其他选择吗?
【问题讨论】:
标签: c# multithreading unity3d callback
你可以使用 async/await..
async void MyFunc()
{
await Task.Run(() => { /* your work in thread */ });
//Your work is finished at this point
}
另外,您可以用 try-catch 块包围它,并以智能的方式捕获您工作中可能发生的异常。
【讨论】:
async void 很危险,最好使用async Task 作为返回类型
//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
}
【讨论】: