w0051977
w0051977

Reputation: 15787

Executing a Callback Method When an Asynchronous Call Completes

I am trying to learn more about Asynchronous calls, which are part of the MCSD exam. I have followed all of the examples on the following page successfully: http://msdn.microsoft.com/en-gb/library/2e08f6yc.aspx.

I have created console applications and Winform applications for all of the examples. However, the callback function is never called in the last example (Executing a Callback Method When an Asynchronous Call Completes) if a WinForm application is used. Please see the code below:

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

Why is CallbackMethod never reached in a WinForm application? Please note that I understand the difference between a Console application and a WinForm application.

Upvotes: 1

Views: 5222

Answers (1)

Nico Schertler
Nico Schertler

Reputation: 32587

The problem is the Console.ReadLine(). In a WinForms app this call does not block. Instead you can use Thread.Sleep(Timeout.Infinite) or whatever suits your needs best.

Upvotes: 2

Related Questions