O'Reilly logo

Programming Visual Basic .NET, Second Edition by Jesse Liberty

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

Delegates and Callback Mechanisms

There are two ways to get your laundry done. The first way is to put your laundry into the machine, put in a few quarters and then wait for the machine to run. You wait. And then you wait. About 30 minutes later the machine stops and you take your laundry back.

The second way to get your laundry done is to take it to the Laundromat and say “Here, please clean this clothing and call me back when you are done. Here’s my cell number.” The person in the Laundromat does the work while you go off and do something else. When your laundry is done, they call you and say “Your clothes are clean. Your pick up number is 123.” When you return, you give the person at the desk the number 123, and you get back your clean clothes.

The .NET Framework supports the notion of a “callback.” (Callbacks have been in use for many years, and Windows programmers have been using callbacks at least since Win 3.x.) The idea of a callback is that you say to a method, “Do this work, and call me back when you are done.” It is a simple and clean mechanism for multitasking.

The .NET Framework provides a class, FileStream, which provides asynchronous reading of a file. You do not have to create the threads yourself; FileStream will read the file for you asynchronously, and callback a method you designate when it has data for you, as illustrated in Example 12-4.

Example 12-4. Using callbacks

Option Strict On Imports System Imports System.IO Imports System.Text Public Class AsynchIOTester ...

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