Application.DoEvents()可以在c#中使用吗?

这个函数是一种让GUI赶上应用程序其余部分的方法吗,就像VB6的DoEvents一样?


当前回答

可以,但这只是个黑客。

参见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方法。

可以,但这只是个黑客。

参见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只会给我带来痛苦。

根据我的经验,我建议在。net中使用DoEvents时要非常谨慎。当在包含DataGridViews的TabControl中使用DoEvents时,我经历了一些非常奇怪的结果。另一方面,如果你所处理的只是一个带有进度条的小表单,那么它可能是OK的。

底线是:如果要使用DoEvents,那么在部署应用程序之前需要彻底测试它。

我见过许多使用“DoEvents-Hack”的商业应用程序。特别是当渲染开始发挥作用时,我经常看到这样的情况:

while(running)
{
    Render();
    Application.DoEvents();
}

他们都知道这种方法的害处。然而,他们使用黑客,因为他们不知道任何其他解决方案。以下是Tom Miller的博客文章中的一些方法:

Set your form to have all drawing occur in WmPaint, and do your rendering there. Before the end of the OnPaint method, make sure you do a this.Invalidate(); This will cause the OnPaint method to be fired again immediately. P/Invoke into the Win32 API and call PeekMessage/TranslateMessage/DispatchMessage. (Doevents actually does something similar, but you can do this without the extra allocations). Write your own forms class that is a small wrapper around CreateWindowEx, and give yourself complete control over the message loop. -Decide that the DoEvents method works fine for you and stick with it.

Yes.

但是,如果您需要使用应用程序。DoEvents,这主要是一个糟糕的应用程序设计的指示。也许你想在一个单独的线程中做一些工作?