Sunday, January 6, 2008

.NET Reference Guide > Asynchronous Reads

InformIT: .NET Reference Guide - Asynchronous Reads


Dim BUFFER_SIZE As Integer = 10000

Dim data(BUFFER_SIZE) As Byte

' open a file for asynchronous input
Dim fs As New FileStream("readtest.dat", FileMode.Open, _
FileAccess.Read, FileShare.Read, 1, True)

' initiate an asynchronous read
Dim ar As IAsyncResult = fs.BeginRead(data, 0, BUFFER_SIZE, Nothing, Nothing)

' read is occurring in the background.
' Program can do other processing here.

' When you're ready to access the read data, check for completion
ar.AsyncWaitHandle.WaitOne()

' harvest the result
Dim bytesRead As Integer = fs.EndRead(ar)

Console.WriteLine("{0} bytes read", bytesRead)


You poll by checking the AsyncWaitHandle.Completed flag, like this:

While Not ar.IsCompleted
Console.Write(".")
System.Threading.Thread.Sleep(10)
End While