Asynchronous IO

Asynchronous I/O

As you've seen, you can add threading to any type of code by placing it into a separate method and creating a delegate. In addition, the .NET Framework also includes asynchronous support in many classes, particularly those that deal with streams (and hence the code you use for direct socket connections over a network, downloading Web pages, and writing or reading files). You can recognize these methods by their name. When asynchronous methods exist, they always take the same name as the synchronous method versions, with Begin or End added to the beginning.

For example, you can use the FileStream.BeginWrite method to start an asynchronous write operation. This can enable you to save a large amount of data to disk without waiting for it to be completely written.

Here's how you initiate the operation:

 Dim fs As New FileStream("c:\myfile.bmp", FileMode.Create, _                          FileAccess.Write, FileShare.None) fs.BeginWrite(ByteBuffer, 0, ByteBuffer.Length, _               AddressOf FileWriteCallback, fs) 

The following code is the callback that enables you to verify that it completed successfully. Note that because this code stores the FileStream as the state object, you can start any number of asynchronous file writing operations without any danger of getting them confused with each other.

 Public Sub FileWriteCallback(ByVal ar As IAsyncResult)     Dim fs As FileStream = CType(ar.AsyncState, FileStream)     fs.EndWrite(ar)     fs.Close() End Sub 


Microsoft. NET Distributed Applications(c) Integrating XML Web Services and. NET Remoting
MicrosoftВ® .NET Distributed Applications: Integrating XML Web Services and .NET Remoting (Pro-Developer)
ISBN: 0735619336
EAN: 2147483647
Year: 2005
Pages: 174

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net