We have seen how we can use the APM design pattern that is implemented in the FileStream
class to perform an asynchronous read and then wait on the results. We also mentioned how we can poll to see if the asynchronous read has completed instead of blocking the main thread. Now, we will see how we can execute a delegate method when the asynchronous read has completed.
Using this method, we do not have to block the main thread waiting or perform the work of polling the IsCompleted
property to see when the read has completed. We simply execute the BeginRead
method and pass it a delegate method. We then go on our way and, when the read completes, the delegate method will be executed.
Let's look at the method header for the BeginRead
method of the FileStream
class. The following is the method definition:
public override IAsyncResult BeginRead( byte[] array, int offset, int numBytes, AsyncCallback userCallback, Object stateObject )
You will see...