Recently, I've decided to start refining my skills with Asynchronous methods. Paul Kimmel's Visual Basic .NET Power Coding has a tremendous discussion of Asnychronous programming and I really liked his example of Asynchronous File IO. Here's a really cool Example. We know that .NET keeps with specific naming conventions and usually you can tell something is asynchronous if it begins with "Begin" So let's take a look at how to read a file Asynchronously:
Since we are going to refer to some variables from within our async method, we need two module level variables:
| Private Stream As FileStream = Nothing Private Data() As Byte |
| Private Sub BeginProcess(ByVal File_Name As String) If Not (Stream Is Nothing) Then Return Stream = New FileStream(File_Name, FileMode.Open) ReDim Data(Stream.Length) Stream.BeginRead(Data, 0, Stream.Length, AddressOf Finished, Nothing) MessageBox.Show("BeginProcess") End Sub Private Sub Finished(ByVal Result As IAsyncResult) Dim BytesRead = Stream.EndRead(Result) TextBox1.Text = System.Text.ASCIIEncoding.ASCII.GetString(Data) Stream.Close() Stream = Nothing MessageBox.Show("Finished") End Sub |
| Private Sub BeginProcess(ByVal File_Name As String) If Not (Stream Is Nothing) Then Return Stream = New FileStream(File_Name, FileMode.Open) ReDim Data(Stream.Length) Stream.BeginRead(Data, 0, Stream.Length, AddressOf Finished, Nothing) MessageBox.Show("BeginProcess") End Sub Private Sub Finished(ByVal Result As IAsyncResult) TextBox1.Text = System.Text.ASCIIEncoding.ASCII.GetString(Data) Stream.Close() Stream = Nothing MessageBox.Show("Finished") End Sub |