|
-
Oct 4th, 2011, 02:24 PM
#2
Re: Use controls while a loop is running?
There are two solutions, one is easy, the other more complicated.
1) Application.DoEvents inside the loop.
2) Move the loops into a BackGroundWorker component or into a different thread (same result, different techniques).
What you need to be able to do is to have the process pumping the message queue while the loop is running. Application.DoEvents pauses the loop to let the application pump the message queue. That will work, but it has a bit of overhead. If the inner loop is really fast, then put this line in the outer loop such that the DoEvents is called once per iteration of the outer loop. If the inner loop is slow, then put the DoEvents inside the inner loop. For the app to be responsive, you want this method to be called at a frequency of once every half second, or so, which gives you an idea of where in the loops you want it. If it is only called every second, the controls will appear to lag. Longer than that and the app will appear frozen. I have successfully used this to keep controls responsive in a loop that ran for three days at a time.
The second alternative is to shift the long running stuff into a different thread. This leaves the UI thread free to handle messages as they arise since it is no longer occupied with the loop. Threads are more difficult to set up, though only moderately so, but threads are also the preferred solution to this problem. For reasons that I don't really understand, people are a bit opposed to DoEvents. It does have a cost, so you don't want to be calling it a thousand times a second, but anything short of that works fine.
My usual boring signature: Nothing
 
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|