Imports System
Imports System.Threading
Imports System.Runtime.InteropServices
Public Class Form1
' The delegate must have the same signature as the method
' it will call asynchronously.
Public Delegate Function AsyncMethodCaller(<Out> ByRef threadId As Integer) As String
' The method to be executed asynchronously.
Public Function TestMethod(<Out> ByRef threadId As Integer) As String
Thread.Sleep(5000)
threadId = Thread.CurrentThread.ManagedThreadId()
Return "hello world"
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' The asynchronous method puts the thread id here.
Dim threadId As Integer
'this is a form that pops up and asks us to be patient
Dim frmPleaseWait As New PleaseWait
frmPleaseWait.Show()
' Create the delegate.
Dim caller As New AsyncMethodCaller(AddressOf TestMethod)
' Initiate the asynchronous call.
Dim result As IAsyncResult = caller.BeginInvoke(threadId, Nothing, Nothing)
' Call EndInvoke to Wait for the asynchronous call to complete,
' and to retrieve the results.
Dim returnValue As String = caller.EndInvoke(threadId, result)
frmPleaseWait.Close()
Dim strMessage As String = String.Format("The call executed on thread {0}, with return value ""{1}"".", threadId, returnValue)
MsgBox(strMessage)
End Sub
End Class