views:

519

answers:

2

Hi what is the necessity of using Application.DoEvents and when we should use it?

+1  A: 

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.

Martin Moser
+7  A: 

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.

Jon Skeet
Jon, you said that to make sure events get handled periodically...which events? in a sequential programming, suppose we have a button on a form. when user clicks, for example the opacity of the form changes...now, what kind of events are there here except for button's click?
odiseh
Repaints, resizes, mouse movements etc. There are an awful lot of events, even if your application code doesn't explicitly handle most of them.
Jon Skeet