简体   繁体   English

在等待委托完成时让UI线程继续运行吗?

[英]Keep UI thread going while waiting for a delegate to finish?

In my code I use BeginInvoke to fire off a delegate (to load some config from a file). 在我的代码中,我使用BeginInvoke触发委托(从文件加载一些配置)。 I want my UI to keep responsive, so I thought doing something like this would work: 我希望我的UI保持响应,所以我想这样做是可行的:

  LoadConfig lc = new LoadConfig(doLoadConfig);
  IAsyncResult asyncResult = lc.BeginInvoke(null, null);
  while (!asyncResult.IsCompleted)
  {
    asyncResult.AsyncWaitHandle.WaitOne(500, false);
  }
  asyncResult.AsyncWaitHandle.Close();
  bool bLoadResult = lc.EndInvoke(asyncResult);

Problem is it hangs on the waiting bit. 问题是它挂在等待位上。 Is there any way for me to wait for my delegate to finish while keeping the UI thread alive (kind of like using async / await in .NET 4.5)? 有什么办法让我等待委托完成,同时保持UI线程处于活动状态(类似于在.NET 4.5中使用async / await )?

I'm using .NET 3.5 BTW. 我正在使用.NET 3.5 BTW。

So are callbacks my only option then? 那么,回调是我唯一的选择吗?

I know it's tempting to use polling with DoEvents , but that'd be wrong. 我知道在DoEvents使用轮询很诱人,但这是错误的。 To keep the UI responsive, you need to yield back to the UI thread message loop. 为了使UI保持响应,您需要让步回到UI线程消息循环。 Ie, you have to return from current method, and handle the completion event asynchronously (via the callback), when it's fired in the future. 也就是说,当将来触发时,您必须从当前方法返回并异步处理完成事件(通过回调)。

In C# 5.0, there's async/await to solve the callback hell problem. 在C#5.0中,存在async/await来解决回调地狱问题。 In earlier versions, you could exploit yield keyword, like this . 在早期版本中,您可以利用yield关键字,例如this

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

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