Using Asynchronous File I/OBy 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
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. |