Я пытаюсь узнать больше об асинхронных вызовах, которые являются частью экзамена 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()'? Вызывается ли сама асинхронная функция? –
@ Нико Шертлер, да. Я отключал «включить инфраструктуру приложения», и основной метод был достигнут. – w0051977