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 ...

Get Programming Visual Basic .NET, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.