.NET Development - Calling a subroutine asynchronously and waiting for the response

Calling a subroutine asynchronously and waiting for the response

I routinely need to call a stored procedure and wait 30 seconds for the response. The user is left wondering if there's anyone home. I can't open a 'please wait' dialog because the interface is frozen. Enter async.

Async calls have been around for a while, I see articles going back to 2009 and earlier, .NET 4.5 really brags about its multi-threading capabilities.

My needs are simpler. This article (written against .NET 3.5) is a short, simple block of code that show how to call a subroutine asynchronously and wait for the result.

In this example we have a second form called 'pleaseWait', it pops up and then disappears when the function returns

 

 

Related Articles

... and you 'll find more on the NET Development Menu

 

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

RealWorldCode gives developers practical, real‑world solutions with clean, working code — no fluff, no theory, just answers.
Links
Home
Knowledge Areas
Sitemap
Contact
Et cetera
Privacy Policy
Terms and Conditions
Cookie Preferences