Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 703
Kredns Avatar asked Dec 10 '22 21:12

Kredns


1 Answers

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.

like image 160
Phil Wright Avatar answered Jan 02 '23 18:01

Phil Wright