Search Tools Links Login

Using DoEvents to Make Your Apps CPU-Friendly


How to keep your VB application from being a CPU hog using DoEvents.

Original Author: James Vincent Carnicelli

Code

If you are a new VB programmer and have begun to develop more sophisticated applications to do animations, heavy number crunching, etc., you may have noticed that sometimes those apps seem to take control of Windows while they run. For example, your mouse clicks and keystrokes may take a long time to register with your app and others. You may not even see your mouse moving with you fast enough.

The good news is that it's fairly easy to correct this problem.

While newer versions of Windows support "simultaneous" multitasking using "time slices" for each process, Windows is still a non-preemptive operating system at its core. "Preemptive multitasking" means that the operating system (OS) gives each running process a slice of time running on the CPU before it interrupts it to give CPU control to the next process. Each process need not care about the CPU needs of any other. "Nonpreemptive multitasking" means that the processes are expected to voluntarily yield control of the CPU to the OS so it can give control to the next running program.

Roughly speaking, if you're not somehow giving control of the CPU back to Windows, other apps can't use it.

Most simple VB programs get control when Windows triggers an event, like a button click or mouse movement. If your app responds to the event, it automatically gives control back to Windows when the responding event (e.g., Command1_Click() ) is done executing. But if it doesn't exit within a few seconds, you may start to notice your app is hogging resources.

Fortunately, VB comes with a built in routine to voluntarily give control of the CPU back to Windows for a while: DoEvents. Consider the following simple program:


Notice how DoEvents is used in Form_Unload() to let the loop initiated in Command1_Click(), if it's still running, finish and exit? That's right; one chunk of your own code can be running "in parallel" with another chunk in your program. You don't have to mess with multithreading or multiprocessing to have this happen. This is another benefit of using DoEvents liberally and carefully.

In summary, use DoEvents to break up algorithms that take a long time or loop continuously to give Windows a chance now and then to do other things with the CPU.

About this post

Posted: 2002-06-01
By: ArchiveBot
Viewed: 75 times

Categories

Visual Basic 6

Attachments

No attachments for this post


Loading Comments ...

Comments

No comments have been added for this post.

You must be logged in to make a comment.