O'Reilly logo

Visual Basic 2012 Programmer's Reference by Rod Stephens

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

ASYNCHRONOUS METHODS

Normally a program calls a routine and control passes to that routine. When the routine finishes executing, control returns to the calling code, which resumes executing its own code. All of this happens synchronously so the calling code waits until the called routine finishes all of its work before it continues.

Visual Basic provides several methods that you can use to execute code asynchronously. In those cases a calling piece of code can launch a routine in a separate thread and continue executing before the routine finishes. If your computer has multiple cores or CPUs, the calling code and the asynchronous routine may both be able to execute simultaneously on separate processors, potentially saving a lot of time.

Visual Basic provides several methods of various difficulties for executing code asynchronously. The following sections describe three of the more manageable approaches.

Calling EndInvoke Directly

This method uses a delegate’s BeginInvoke method to start a routine executing asynchronously. Later the code calls EndInvoke to wait for the routine to finish and to process the result.

To use this method, first define a delegate that represents the routine that you want to run asynchronously. Call the delegate’s BeginInvoke method, passing it whatever parameters the method needs plus two additional parameters: a callback method and a parameter to pass to the callback method. For this technique, set the extra parameters to Nothing so the routine does not ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required