2013-02-26 139 views
1

我想了解更多关于异步调用的信息,这些调用是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 

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

+0

您是否已将WinForms项目配置为在Main()方法中启动?异步函数本身是否被调用? – 2013-02-26 14:48:36

+0

@Nico Schertler,是的。我没有选择'启用应用程序框架',并且主要方法已经达成。 – w0051977 2013-02-26 14:51:08

回答

2

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

+0

你能解释一下你的意思吗?我对异步处理相对较新。 – w0051977 2013-02-26 14:59:24

+0

它虽然工作。 +1。 – w0051977 2013-02-26 15:00:11

+0

在控制台应用程序中'ReadLine()'不会返回,直到用户返回。所以'Main()'不会被留下。 WinForms并非如此。因此,在异步调用返回之前,“Main()”被保留。由于异步调用是后台线程,因此应用程序将退出,因为不再有前台线程。 – 2013-02-26 15:14:27

相关问题