Reputation: 195
I'm writing a data visual tool for my team and need to read a data file once the windows Form opens. The binary data file is large and can take quite a few seconds to load depending on connection speed of the user's PC to the file's network location. My limited asynchronous programming knowledge produced the following framework. The data loading still freezes the UI, which is the thing I would like to avoid. Can someone give some help on this matter?
Public Class Form1
Public db_path as string = "db path string"
Private Async Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
TextBox1.Text = "Loading..."
Dim sample_num As Integer = Await read_DB(db_path)
TextBox1.Text = "Sample count: " & sample_num.ToString
End Sub
Private Async Function read_DB(db_path as String) As Task(Of Integer)
Dim sample_num As Integer = 0
If (File.Exists(db_path)) Then
Try
Using reader As BinaryReader = New BinaryReader(File.Open(db_path, FileMode.Open, FileAccess.Read))
sample_num = reader.ReadInt32()
' Read the DB file here
Next
End Using
Catch Ex As Exception
Finally
End Try
Else
End If
Return sample_num
End Function
End Class
Upvotes: 0
Views: 94
Reputation: 103
Here is what you should do
Public Class Form1
Public db_path As String = "db path string"
Private Async Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
TextBox1.Text = "Loading..."
Dim sample_num As Integer
Await Task.Run(Sub() sample_num = read_DB(db_path))
TextBox1.Text = "Sample count: " & sample_num.ToString
End Sub
Private Function read_DB(db_path As String) As Integer
Dim sample_num As Integer = 0
If (File.Exists(db_path)) Then
Try
Using reader As BinaryReader = New BinaryReader(File.Open(db_path, FileMode.Open, FileAccess.Read))
sample_num = reader.ReadInt32()
' Read the DB file here
Next
End Using
Catch Ex As Exception
Finally
End Try
Else
End If
Return sample_num
End Function
End Class
Upvotes: 1