Application.DoEvents()可以在c#中使用吗?
这个函数是一种让GUI赶上应用程序其余部分的方法吗,就像VB6的DoEvents一样?
Application.DoEvents()可以在c#中使用吗?
这个函数是一种让GUI赶上应用程序其余部分的方法吗,就像VB6的DoEvents一样?
当前回答
请查阅应用程序的MSDN文档。DoEvents方法。
其他回答
Yes.
但是,如果您需要使用应用程序。DoEvents,这主要是一个糟糕的应用程序设计的指示。也许你想在一个单独的线程中做一些工作?
应用程序。如果在消息队列中放入图形处理以外的内容,DoEvents可能会产生问题。
它可以用于更新进度条,并在MainForm构造和加载等过程中通知用户进度(如果这需要一段时间)。
In a recent application I've made, I used DoEvents to update some labels on a Loading Screen every time a block of code is executed in the constructor of my MainForm. The UI thread was, in this case, occupied with sending an email on a SMTP server that didn't support SendAsync() calls. I could probably have created a different thread with Begin() and End() methods and called a Send() from their, but that method is error-prone and I would prefer the Main Form of my application not throwing exceptions during construction.
可以,但这只是个黑客。
参见DoEvents邪恶吗?
直接从开发人员引用的MSDN页面:
Calling this method causes the current thread to be suspended while all waiting window messages are processed. If a message causes an event to be triggered, then other areas of your application code may execute. This can cause your application to exhibit unexpected behaviors that are difficult to debug. If you perform operations or computations that take a long time, it is often preferable to perform those operations on a new thread. For more information about asynchronous programming, see Asynchronous Programming Overview.
因此微软对它的使用提出了警告。
此外,我认为这是一个黑客,因为它的行为是不可预测的,容易产生副作用(这来自于尝试使用DoEvents而不是旋转一个新线程或使用后台工作)。
这里没有大男子主义——如果它是一个强有力的解决方案,我会全力支持它。然而,尝试在。net中使用DoEvents只会给我带来痛苦。
请查阅应用程序的MSDN文档。DoEvents方法。
我看到了上面jheriko的评论,最初我同意,如果你最终旋转你的主UI线程,等待另一个线程上长时间运行的异步代码来完成,我无法找到一种避免使用DoEvents的方法。但是根据Matthias的回答,我的UI上一个小面板的简单刷新可以取代DoEvents(并避免一个讨厌的副作用)。
更多关于我案子的细节…
我正在做以下(在这里建议),以确保进度条类型的启动屏幕(如何显示“加载”覆盖…)在长时间运行SQL命令期间更新:
IAsyncResult asyncResult = sqlCmd.BeginExecuteNonQuery();
while (!asyncResult.IsCompleted) //UI thread needs to Wait for Async SQL command to return
{
System.Threading.Thread.Sleep(10);
Application.DoEvents(); //to make the UI responsive
}
缺点:对我来说,调用DoEvents意味着鼠标点击有时会触发启动画面后面的表单,即使我把它设置为TopMost。
好的/答案:用一个简单的刷新调用替换DoEvents行到我的启动画面中心的一个小面板,FormSplash.Panel1.Refresh()。UI更新得很好,其他人警告过的DoEvents怪异现象也消失了。