Visual Basic Concepts

Allowing Users to Interrupt Tasks

During long background tasks, your application cannot respond to user input. Therefore, you should provide the user with a way to interrupt or cancel the background processing by writing code for either the mouse or keyboard events. For example, when a long background task is running, you can display a dialog box that contains a Cancel button that the user can initiate by clicking the ENTER key (if the focus is on the Cancel button) or by clicking on it with the mouse.

Note   You may also want to give the user a visual cue when a long task is processing. For example, you might show the user how the task is progressing (using a Label or Gauge control, for instance), or by changing the mouse pointer to an hourglass.

There are several techniques, but no one way, to write code to handle background processing. One way to allow users to interrupt a task is to display a Cancel button and allow its Click event to be processed. You can do this by placing the code for your background task in a timer event, using the following guidelines.

  • Use static variables for information that must persist between occurrences of the Timer event procedure.

  • When the Timer event gets control, allow it to run slightly longer than the time you specified for the Interval property. This ensures that your background task will use every bit of processor time the system can give it. The next Timer event will simply wait in the message queue until the last one is done.

  • Use a fairly large value — five to ten seconds — for the timer's Interval property, as this makes for more efficient processing. Preemptive multitasking prevents other applications from being blocked, and users are generally tolerant of a slight delay in canceling a long task.

  • Use the Enabled property of the Timer as a flag to prevent the background task from being initiated when it is already running.

For More Information   See "Using the Timer Control" in "Using Visual Basic's Standard Controls."