5.10. Read a File Asynchronously

Problem

You need to read data from a file without blocking the execution of your code. This technique is commonly used if the file is stored on a slow backing store (such as a networked drive in a wide area network).

Solution

Create a separate class that will read the file asynchronously. Start reading a block of data using the FileStream.BeginRead method and supply a callback method. When the callback is triggered, retrieve the data by calling FileStream.EndRead, process it, and read the next block asynchronously with BeginRead.

How It Works

The FileStream includes basic support for asynchronous use through the BeginRead and EndRead methods. Using these methods, you can read a block of data on one of the threads ...

Get Visual Basic 2008 Recipes: A Problem-Solution Approach 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.