What is the necessity of using Application.DoEvents
and when we should use it?
问题:
回答1:
Application.DoEvents
is usually used to make sure that events get handled periodicaly when you're performing some long-running operation on the UI thread.
A better solution is just not to do that. Perform long-running operations on separate threads, marshalling to the UI thread (either using Control.BeginInvoke
/Invoke
or with BackgroundWorker
) when you need to update the UI.
Application.DoEvents
introduces the possibility of re-entrancy, which can lead to very hard-to-understand bugs.
回答2:
Windows maintains a queue to hold various events like click, resize, close, etc. While a control is responding to an event, all other events are held back in the queue. So if your application is taking unduly long to process a button-click, rest of the application would appear to freeze. Consequently it is possible that your application appears unresponsive while it is doing some heavy processing in response to an event. While you should ideally do heavy processing in an asynchronous manner to ensure that the UI doesn’t freeze, a quick and easy solution is to just call Application.DoEvents() periodically to allow pending events to be sent to your application.
For good windows application, end user doesn’t like when any form of application are freezing out while performing larger/heavyweight operation. User always wants application run smoothly and in responsive manner rather than freezing UI. But after googling i found that Application.DoEvents() is not a good practice to use in application more frequently so instead this events it’s better to use BackGround Worker Thread for performing long running task without freezing windows.
You can get better idea if you practically look it. Just copy following code and check application with and without putting Application.DoEvents().
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
For i As Integer = 0 To 1000
System.Threading.Thread.Sleep(100)
ListBox1.Items.Add(i.ToString())
Application.DoEvents()
Next
End Sub
回答3:
Imho you should more less never use it, as you might end up with very unexpected behavior. Just generated code is ok. Things like you are executing again the event handler you are currently in,because the user pressed a key twice etc etc. If you want to refresh a control to display the current process you should explicitly call .Update on that control in instead of calling Application.DoEvents.