异步功能阻止UI线程中的IOException

时间:2015-02-19 03:26:31

标签: .net vb.net multithreading asynchronous async-await

使用以下代码,如果“找不到网络路径”,它将完全阻止UI最多15秒。如果我用Await Task.Delay(5000)替换代码,则不会。就像open FileStream没有异步发生......

如何在不阻止UI的情况下处理此方案?

有关信息,我正在尝试异步读取一行(1kb)文本文件。

Private Async Function getDataAsync(filepath As String, ct As CancellationToken) As Task(Of String)
    Dim data as string
    Try
        Using sourceStream As New FileStream(filepath, FileMode.Open, FileAccess.Read,
                                             FileShare.Read, bufferSize:=4096, useAsync:=True)
            Dim reader As New StreamReader(sourceStream)
            data = Await reader.ReadLineAsync()
        End Using
    Catch ex As Exception
        data = ex.Message
    End Try

    Return data
End Function

1 个答案:

答案 0 :(得分:1)

问题是执行始终是同步的,直到第一个Await

尝试这样的事情:

Private Async Function getDataAsync(filepath As String, ct As CancellationToken) As Task(Of String)
    Return Await Task.Run(Function()
        Dim data as string
        Try
            Using sourceStream As New FileStream(filepath, FileMode.Open, FileAccess.Read,
                                                 FileShare.Read, bufferSize:=4096, useAsync:=True)
                Dim reader As New StreamReader(sourceStream)
                data = Await reader.ReadLineAsync()
            End Using
        Catch ex As Exception
            data = ex.Message
        End Try
        Return data
    End Function)
End Function