关于数据加载,UI冻结的异步任务

时间:2015-07-23 05:57:03

标签: vb.net asynchronous

我正在为我的团队编写数据可视化工具,并且需要在Windows窗体打开后读取数据文件。二进制数据文件很大,可能需要几秒钟才能加载,具体取决于用户PC与文件网络位置的连接速度。我有限的异步编程知识产生了以下框架。数据加载仍然冻结了UI,这是我想避免的。有人可以就此事提供一些帮助吗?

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

1 个答案:

答案 0 :(得分:1)

这是你应该做的事情

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