C# – Application.DoEvents();


How do I keep my C# form that, lets say is in a for-loop, from locking up? Do I call Application.DoEvents(); before the loop or after? From what I've heard using the DoEvents method will keep my app from locking.

Best Solution

You should not use Application.DoEvents() in order to keep your application responsive.

Calling this method will allow any waiting windows messages to be dispatched. This means if a user clicks on a button (or performs any other user interaction) that action will be processed. This can therefore cause reentrancy. If they press the same button as the one that caused the loop you are processing you will end up having the routine called again before you have finished!

Instead you should use a BackgroundWorker thread to perform the long process and then once the action is completed perform whatever additional actions are required. For example, once a button is pressed you would start the worker thread and then disable you button so it cannot be pressed again. Once the worker thread completes you would enable the button again.