我想了解更多关于异步调用的信息,这些调用是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应用程序之间的区别。
您是否已将WinForms项目配置为在Main()方法中启动?异步函数本身是否被调用? – 2013-02-26 14:48:36
@Nico Schertler,是的。我没有选择'启用应用程序框架',并且主要方法已经达成。 – w0051977 2013-02-26 14:51:08