Using Asynchronous File IO

Using Asynchronous File I/O

By default, when you read data from a file or write data to a file, the operation is synchronous. A synchronous operation is one where the code will attempt to complete the operation before continuing on to the next line of code. So, if it takes your code 20 minutes to perform a read operation of an entire file, the next line of code in your application will have to wait 20 minutes before executing.

This kind of waiting behavior is usually frowned upon by end users: No one wants to sit and twiddle their thumbs while an application locks everything up to complete an incredibly long operation.

This chapter does not go into too much detail on how to accomplish multithreaded programming, as more will be discussed on that topic later in the book. However, you will see that asynchronous file I/O is not only possible, but easy if you plan ahead. Take a look at the sample in Listing 7.3.

Listing 7.3. Asynchronous File I/O

using System; using System.IO; using System.Collections.Generic; using System.Text; namespace AsyncFile { class Program { static bool fileDone = false; static FileStream fs = null; static void Main(string[] args) {     fs = new FileStream("quote.txt", FileMode.Open);     byte[] fileBytes = new byte[fs.Length];     fs.BeginRead(fileBytes, 0, (int)fs.Length, new AsyncCallback(ReadEnd), null);     while (!fileDone)     {         Console.WriteLine("Waiting for file read to finish...");     }     Console.ReadLine(); } static void ReadEnd(IAsyncResult ar) {     int bytesRead = fs.EndRead(ar);     Console.WriteLine("Read {0} bytes.", bytesRead);     fs.Close();     fileDone = true; } } } 

A fairly large quote.txt file was created for this example. If you run it with that file, you should see that the message "Waiting for file read to finish..." appears several times before the operation is complete. This illustrates that the while loop immediately after the BeginRead method began executing even before the entire file had been read. This gives your application the ability to continue processing and providing the user with a rich experience while the data is being loaded in the background.

The concepts behind the AsyncCallback class and the IAsyncResult interface are covered more in depth throughout this book as the topics become more complex and you explore event-based programming and using multithreaded techniques to improve your application.

Microsoft Visual C# 2005 Unleashed
Microsoft Visual C# 2005 Unleashed
ISBN: 0672327767
EAN: 2147483647
Year: 2004
Pages: 298 © 2008-2017.
If you may any questions please contact us: