异步调用完成时执行回调方法

时间:2013-02-26 14:39:18

标签: vb.net asynchronous

我正在尝试了解有关异步调用的更多信息,这是MCSD考试的一部分。我已成功完成了以下页面上的所有示例:http://msdn.microsoft.com/en-gb/library/2e08f6yc.aspx

我为所有示例创建了控制台应用程序和Winform应用程序。但是,如果使用WinForm应用程序,则在最后一个示例(在异步调用完成时执行回调方法)中永远不会调用回调函数。请参阅以下代码:

Imports System
Imports System.Threading
Imports System.Runtime.InteropServices

Public Class AsyncDemo
    ' The method to be executed asynchronously.
    '
    Public Function TestMethod(ByVal callDuration As Integer, _
            <Out()> ByRef threadId As Integer) As String
        Console.WriteLine("Test method begins.")
        Thread.Sleep(callDuration)
        threadId = AppDomain.GetCurrentThreadId()
        Return "MyCallTime was " + callDuration.ToString()
    End Function
End Class

' The delegate must have the same signature as the method
' you want to call asynchronously.
Public Delegate Function AsyncDelegate(ByVal callDuration As Integer, _
    <Out()> ByRef threadId As Integer) As String

Public Class AsyncMain
    ' The asynchronous method puts the thread id here.
    Private Shared threadId As Integer

    Shared Sub Main()
        ' Create an instance of the test class.
        Dim ad As New AsyncDemo()

        ' Create the delegate.
        Dim dlgt As New AsyncDelegate(AddressOf ad.TestMethod)

        ' Initiate the asynchronous call.
        Dim ar As IAsyncResult = dlgt.BeginInvoke(3000, _
            threadId, _
            AddressOf CallbackMethod, _
            dlgt)

        Console.WriteLine("Press Enter to close application.")
        Console.ReadLine()
    End Sub

    ' Callback method must have the same signature as the
    ' AsyncCallback delegate.
    Shared Sub CallbackMethod(ByVal ar As IAsyncResult)
        ' Retrieve the delegate.
        Dim dlgt As AsyncDelegate = CType(ar.AsyncState, AsyncDelegate)

        ' Call EndInvoke to retrieve the results.
        Dim ret As String = dlgt.EndInvoke(threadId, ar)

        Console.WriteLine("The call executed on thread {0}, with return value ""{1}"".", threadId, ret)
    End Sub
End Class

为什么WinForm应用程序中从未到达CallbackMethod?请注意,我理解控制台应用程序和WinForm应用程序之间的区别。

1 个答案:

答案 0 :(得分:2)

问题是Console.ReadLine()。在WinForms应用程序中,此调用不会阻止。相反,您可以使用Thread.Sleep(Timeout.Infinite)或最适合您需求的任何内容。