网页永远不会异步加载

时间:2016-11-15 15:24:59

标签: asp.net vb.net asynchronous

请参阅以下代码:

    Public Shared Async Sub AsyncMain()
        Dim a As AsyncronousTest = New AsyncronousTest
        Dim task As Task = a.LoadWebpage()

        Do While 1 = 1
            If a.bool = True Then
                Exit Do
            End If
        Loop
        MsgBox("test")
    End Sub

Public Class AsyncronousTest

    Public bool As Boolean = False

    Public Sub Callback()
        bool = True
    End Sub

    Public Async Function LoadWebpage() As Task(Of Integer)
        Dim webC As WebClient = New WebClient()
        Dim newUri As Uri = New Uri("http://webpagetocache")
        Dim task1 As Task = webC.DownloadStringTaskAsync(newUri)
        Await task1
        Callback()
        Return 1
    End Function
End Class
永远无法达到

msgbox("test")。为什么?

这样做的目的是在一夜之间加载网页,以便可以使用asp.net缓存它。

1 个答案:

答案 0 :(得分:0)

您正在调用LoadWebPage并且它正在返回任务,但此任务从未执行,因此LoadWebPage内的实际代码永远不会执行。 您需要执行任务才能执行它。

Public Async Sub AsyncMain()
    Dim a As AsyncronousTest = New AsyncronousTest
    Dim task As Task(Of Integer) = a.LoadWebpage() ' Here you generate the task

    Dim actualResult = Await task ' Here you perform the task

    Do While 1 = 1
        If a.bool = True Then
            Exit Do
        End If
    Loop

    MsgBox("test")
End Sub