Chamando métodos síncronos de forma assíncrona
O .NET permite que você chame qualquer método de maneira assíncrona. Para isso, você define um delegado com a mesma assinatura do método que deseja chamar. O Common Language Runtime define os métodos BeginInvoke
e EndInvoke
automaticamente para esse delegado, com as assinaturas apropriadas.
Observação
Chamadas assíncronas de delegado, especificamente os métodos BeginInvoke
e EndInvoke
, não têm suporte no .NET Compact Framework.
O método BeginInvoke
inicia a chamada assíncrona. Ele tem os mesmos parâmetros que o método que você deseja executar de forma assíncrona, além de outros dois parâmetros opcionais. O primeiro parâmetro é um delegado AsyncCallback que faz referência a um método a ser chamado quando a chamada assíncrona é concluída. O segundo parâmetro é um objeto definido pelo usuário que passa informações para o método de retorno de chamada. BeginInvoke
retorna imediatamente e não espera a conclusão da chamada assíncrona. BeginInvoke
retorna um IAsyncResult, que pode ser usado para monitorar o andamento da chamada assíncrona.
O método EndInvoke
recupera os resultados da chamada assíncrona. Ele pode ser chamado a qualquer momento após BeginInvoke
. Se a chamada assíncrona não for concluída, EndInvoke
bloqueará o thread de chamada até que seja concluída. Os parâmetros de EndInvoke
incluem os parâmetros out
e ref
(<Out>
ByRef
e ByRef
no Visual Basic) do método que você deseja executar de forma assíncrona, além do IAsyncResult retornado por BeginInvoke
.
Observação
O recurso IntelliSense no Visual Studio exibe os parâmetros de BeginInvoke
e EndInvoke
. Se você não estiver usando o Visual Studio ou uma ferramenta semelhante ou se estiver usando C# com Visual Studio, confira APM (Modelo de Programação Assíncrona) para obter uma descrição dos parâmetros definidos para esses métodos.
Os exemplos de código neste tópico demonstram quatro formas comuns de usar BeginInvoke
e EndInvoke
para fazer chamadas assíncronas. Após chamar BeginInvoke
, você pode fazer o seguinte:
Trabalhe um pouco e depois chame
EndInvoke
para bloquear até que a chamada seja concluída.Obtenha um WaitHandle usando a propriedade IAsyncResult.AsyncWaitHandle, use seu método WaitOne para impedir a execução até que o WaitHandle seja sinalizado e, depois, chame
EndInvoke
.Sonde o IAsyncResult retornado por
BeginInvoke
para determinar quando a chamada assíncrona for concluída e, em seguida, chameEndInvoke
.Passe um delegado para um método de retorno de chamada para
BeginInvoke
. O método será executado em um thread ThreadPool quando a chamada assíncrona for concluída. O método de retorno de chamada chamaEndInvoke
.
Importante
Não importa qual técnica você usa, sempre chame EndInvoke
para completar a chamada assíncrona.
Definir o Método de teste e o Delegado assíncrono
Os exemplos de código a seguir demonstram várias maneiras de chamar o mesmo método de longa execução, TestMethod
, de forma assíncrona. O método TestMethod
exibe uma mensagem de console para mostrar que começou a processar, dorme por alguns segundos e, depois, termina. TestMethod
tem um parâmetro out
para demonstrar a maneira como esses parâmetros são adicionados às assinaturas de BeginInvoke
e EndInvoke
. Você pode tratar os parâmetros ref
da mesma forma.
O exemplo de código a seguir mostra a definição de TestMethod
e o delegado chamado AsyncMethodCaller
que pode ser usado para chamar TestMethod
de forma assíncrona. Para compilar os exemplos de código, você deve incluir as definições de TestMethod
e o delegado AsyncMethodCaller
.
using namespace System;
using namespace System::Threading;
using namespace System::Runtime::InteropServices;
namespace Examples {
namespace AdvancedProgramming {
namespace AsynchronousOperations
{
public ref class AsyncDemo
{
public:
// The method to be executed asynchronously.
String^ TestMethod(int callDuration, [OutAttribute] int% threadId)
{
Console::WriteLine("Test method begins.");
Thread::Sleep(callDuration);
threadId = Thread::CurrentThread->ManagedThreadId;
return String::Format("My call time was {0}.", callDuration);
}
};
// The delegate must have the same signature as the method
// it will call asynchronously.
public delegate String^ AsyncMethodCaller(int callDuration, [OutAttribute] int% threadId);
}}}
using System;
using System.Threading;
namespace Examples.AdvancedProgramming.AsynchronousOperations
{
public class AsyncDemo
{
// The method to be executed asynchronously.
public string TestMethod(int callDuration, out int threadId)
{
Console.WriteLine("Test method begins.");
Thread.Sleep(callDuration);
threadId = Thread.CurrentThread.ManagedThreadId;
return String.Format("My call time was {0}.", callDuration.ToString());
}
}
// The delegate must have the same signature as the method
// it will call asynchronously.
public delegate string AsyncMethodCaller(int callDuration, out int threadId);
}
Imports System.Threading
Imports System.Runtime.InteropServices
Namespace Examples.AdvancedProgramming.AsynchronousOperations
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 = Thread.CurrentThread.ManagedThreadId()
return String.Format("My call time was {0}.", callDuration.ToString())
End Function
End Class
' The delegate must have the same signature as the method
' it will call asynchronously.
Public Delegate Function AsyncMethodCaller(ByVal callDuration As Integer, _
<Out> ByRef threadId As Integer) As String
End Namespace
Aguardar uma chamada assíncrona com EndInvoke
A maneira mais simples de executar um método de forma assíncrona é começar a execução do método chamando o método BeginInvoke
do delegado, trabalhar um pouco no thread principal e, depois, chamar o método EndInvoke
do delegado. EndInvoke
pode bloquear o thread de chamada, pois não retorna até que a chamada assíncrona seja concluída. Essa é uma técnica válida para usar com operações de arquivo ou de rede.
Importante
Como EndInvoke
pode bloquear, nunca chame-o a partir de threads que atendem à interface do usuário.
#using <TestMethod.dll>
using namespace System;
using namespace System::Threading;
using namespace Examples::AdvancedProgramming::AsynchronousOperations;
void main()
{
// The asynchronous method puts the thread id here.
int threadId = 2546;
// Create an instance of the test class.
AsyncDemo^ ad = gcnew AsyncDemo();
// Create the delegate.
AsyncMethodCaller^ caller = gcnew AsyncMethodCaller(ad, &AsyncDemo::TestMethod);
// Initiate the asynchronous call.
IAsyncResult^ result = caller->BeginInvoke(3000,
threadId, nullptr, nullptr);
Thread::Sleep(1);
Console::WriteLine("Main thread {0} does some work.",
Thread::CurrentThread->ManagedThreadId);
// Call EndInvoke to wait for the asynchronous call to complete,
// and to retrieve the results.
String^ returnValue = caller->EndInvoke(threadId, result);
Console::WriteLine("The call executed on thread {0}, with return value \"{1}\".",
threadId, returnValue);
}
/* This example produces output similar to the following:
Main thread 1 does some work.
Test method begins.
The call executed on thread 3, with return value "My call time was 3000.".
*/
using System;
using System.Threading;
namespace Examples.AdvancedProgramming.AsynchronousOperations
{
public class AsyncMain
{
public static void Main()
{
// The asynchronous method puts the thread id here.
int threadId;
// Create an instance of the test class.
AsyncDemo ad = new AsyncDemo();
// Create the delegate.
AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);
// Initiate the asynchronous call.
IAsyncResult result = caller.BeginInvoke(3000,
out threadId, null, null);
Thread.Sleep(0);
Console.WriteLine("Main thread {0} does some work.",
Thread.CurrentThread.ManagedThreadId);
// Call EndInvoke to wait for the asynchronous call to complete,
// and to retrieve the results.
string returnValue = caller.EndInvoke(out threadId, result);
Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".",
threadId, returnValue);
}
}
}
/* This example produces output similar to the following:
Main thread 1 does some work.
Test method begins.
The call executed on thread 3, with return value "My call time was 3000.".
*/
Imports System.Threading
Imports System.Runtime.InteropServices
Namespace Examples.AdvancedProgramming.AsynchronousOperations
Public Class AsyncMain
Shared Sub Main()
' The asynchronous method puts the thread id here.
Dim threadId As Integer
' Create an instance of the test class.
Dim ad As New AsyncDemo()
' Create the delegate.
Dim caller As New AsyncMethodCaller(AddressOf ad.TestMethod)
' Initiate the asynchronous call.
Dim result As IAsyncResult = caller.BeginInvoke(3000, _
threadId, Nothing, Nothing)
Thread.Sleep(0)
Console.WriteLine("Main thread {0} does some work.", _
Thread.CurrentThread.ManagedThreadId)
' Call EndInvoke to Wait for the asynchronous call to complete,
' and to retrieve the results.
Dim returnValue As String = caller.EndInvoke(threadId, result)
Console.WriteLine("The call executed on thread {0}, with return value ""{1}"".", _
threadId, returnValue)
End Sub
End Class
End Namespace
'This example produces output similar to the following:
'
'Main thread 1 does some work.
'Test method begins.
'The call executed on thread 3, with return value "My call time was 3000.".
Aguardar uma chamada assíncrona com WaitHandle
Você pode obter um WaitHandle usando a propriedade AsyncWaitHandle do IAsyncResult retornado por BeginInvoke
. O WaitHandle é sinalizado quando a chamada assíncrona é concluída, e você pode esperar por ele chamando o método WaitOne.
Se você usar um WaitHandle, poderá executar um processamento adicional antes ou depois da conclusão da chamada assíncrona, mas antes de chamar EndInvoke
para recuperar os resultados.
Observação
O identificador de espera não é fechado automaticamente quando você chama EndInvoke
. Se você liberar todas as referências para o identificador de espera, os recursos de sistema serão liberados quando a coleta de lixo recuperar o identificador de espera. Para liberar os recursos do sistema assim que você terminar de usar o identificador de espera, descarte-o chamando o método WaitHandle.Close. A coleta de lixo funciona com mais eficiência quando objetos descartáveis são explicitamente descartados.
#using <TestMethod.dll>
using namespace System;
using namespace System::Threading;
using namespace Examples::AdvancedProgramming::AsynchronousOperations;
void main()
{
// The asynchronous method puts the thread id here.
int threadId;
// Create an instance of the test class.
AsyncDemo^ ad = gcnew AsyncDemo();
// Create the delegate.
AsyncMethodCaller^ caller = gcnew AsyncMethodCaller(ad, &AsyncDemo::TestMethod);
// Initiate the asynchronous call.
IAsyncResult^ result = caller->BeginInvoke(3000,
threadId, nullptr, nullptr);
Thread::Sleep(0);
Console::WriteLine("Main thread {0} does some work.",
Thread::CurrentThread->ManagedThreadId);
// Wait for the WaitHandle to become signaled.
result->AsyncWaitHandle->WaitOne();
// Perform additional processing here.
// Call EndInvoke to retrieve the results.
String^ returnValue = caller->EndInvoke(threadId, result);
// Close the wait handle.
result->AsyncWaitHandle->Close();
Console::WriteLine("The call executed on thread {0}, with return value \"{1}\".",
threadId, returnValue);
}
/* This example produces output similar to the following:
Main thread 1 does some work.
Test method begins.
The call executed on thread 3, with return value "My call time was 3000.".
*/
using System;
using System.Threading;
namespace Examples.AdvancedProgramming.AsynchronousOperations
{
public class AsyncMain
{
static void Main()
{
// The asynchronous method puts the thread id here.
int threadId;
// Create an instance of the test class.
AsyncDemo ad = new AsyncDemo();
// Create the delegate.
AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);
// Initiate the asynchronous call.
IAsyncResult result = caller.BeginInvoke(3000,
out threadId, null, null);
Thread.Sleep(0);
Console.WriteLine("Main thread {0} does some work.",
Thread.CurrentThread.ManagedThreadId);
// Wait for the WaitHandle to become signaled.
result.AsyncWaitHandle.WaitOne();
// Perform additional processing here.
// Call EndInvoke to retrieve the results.
string returnValue = caller.EndInvoke(out threadId, result);
// Close the wait handle.
result.AsyncWaitHandle.Close();
Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".",
threadId, returnValue);
}
}
}
/* This example produces output similar to the following:
Main thread 1 does some work.
Test method begins.
The call executed on thread 3, with return value "My call time was 3000.".
*/
Imports System.Threading
Imports System.Runtime.InteropServices
Namespace Examples.AdvancedProgramming.AsynchronousOperations
Public Class AsyncMain
Shared Sub Main()
' The asynchronous method puts the thread id here.
Dim threadId As Integer
' Create an instance of the test class.
Dim ad As New AsyncDemo()
' Create the delegate.
Dim caller As New AsyncMethodCaller(AddressOf ad.TestMethod)
' Initiate the asynchronous call.
Dim result As IAsyncResult = caller.BeginInvoke(3000, _
threadId, Nothing, Nothing)
Thread.Sleep(0)
Console.WriteLine("Main thread {0} does some work.", _
Thread.CurrentThread.ManagedThreadId)
' Perform additional processing here and then
' wait for the WaitHandle to be signaled.
result.AsyncWaitHandle.WaitOne()
' Call EndInvoke to retrieve the results.
Dim returnValue As String = caller.EndInvoke(threadId, result)
' Close the wait handle.
result.AsyncWaitHandle.Close()
Console.WriteLine("The call executed on thread {0}, with return value ""{1}"".", _
threadId, returnValue)
End Sub
End Class
End Namespace
'This example produces output similar to the following:
'
'Main thread 1 does some work.
'Test method begins.
'The call executed on thread 3, with return value "My call time was 3000.".
Sondar a conclusão da chamada assíncrona
Você pode usar a propriedade IsCompleted do IAsyncResult retornado por BeginInvoke
para descobrir quando a chamada assíncrona for concluída. Você pode fazer isso ao fazer a chamada assíncrona de um thread que atenda à interface do usuário. A sondagem da conclusão permite que o thread de chamada continue em execução enquanto a chamada assíncrona é executada em um thread ThreadPool.
#using <TestMethod.dll>
using namespace System;
using namespace System::Threading;
using namespace Examples::AdvancedProgramming::AsynchronousOperations;
void main()
{
// The asynchronous method puts the thread id here.
int threadId;
// Create an instance of the test class.
AsyncDemo^ ad = gcnew AsyncDemo();
// Create the delegate.
AsyncMethodCaller^ caller = gcnew AsyncMethodCaller(ad, &AsyncDemo::TestMethod);
// Initiate the asynchronous call.
IAsyncResult^ result = caller->BeginInvoke(3000,
threadId, nullptr, nullptr);
// Poll while simulating work.
while(result->IsCompleted == false)
{
Thread::Sleep(250);
Console::Write(".");
}
// Call EndInvoke to retrieve the results.
String^ returnValue = caller->EndInvoke(threadId, result);
Console::WriteLine("\nThe call executed on thread {0}, with return value \"{1}\".",
threadId, returnValue);
}
/* This example produces output similar to the following:
Test method begins.
.............
The call executed on thread 3, with return value "My call time was 3000.".
*/
using System;
using System.Threading;
namespace Examples.AdvancedProgramming.AsynchronousOperations
{
public class AsyncMain
{
static void Main() {
// The asynchronous method puts the thread id here.
int threadId;
// Create an instance of the test class.
AsyncDemo ad = new AsyncDemo();
// Create the delegate.
AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);
// Initiate the asynchronous call.
IAsyncResult result = caller.BeginInvoke(3000,
out threadId, null, null);
// Poll while simulating work.
while(result.IsCompleted == false) {
Thread.Sleep(250);
Console.Write(".");
}
// Call EndInvoke to retrieve the results.
string returnValue = caller.EndInvoke(out threadId, result);
Console.WriteLine("\nThe call executed on thread {0}, with return value \"{1}\".",
threadId, returnValue);
}
}
}
/* This example produces output similar to the following:
Test method begins.
.............
The call executed on thread 3, with return value "My call time was 3000.".
*/
Imports System.Threading
Imports System.Runtime.InteropServices
Namespace Examples.AdvancedProgramming.AsynchronousOperations
Public Class AsyncMain
Shared Sub Main()
' The asynchronous method puts the thread id here.
Dim threadId As Integer
' Create an instance of the test class.
Dim ad As New AsyncDemo()
' Create the delegate.
Dim caller As New AsyncMethodCaller(AddressOf ad.TestMethod)
' Initiate the asynchronous call.
Dim result As IAsyncResult = caller.BeginInvoke(3000, _
threadId, Nothing, Nothing)
' Poll while simulating work.
While result.IsCompleted = False
Thread.Sleep(250)
Console.Write(".")
End While
' Call EndInvoke to retrieve the results.
Dim returnValue As String = caller.EndInvoke(threadId, result)
Console.WriteLine(vbCrLf & _
"The call executed on thread {0}, with return value ""{1}"".", _
threadId, returnValue)
End Sub
End Class
End Namespace
' This example produces output similar to the following:
'
'Test method begins.
'.............
'The call executed on thread 3, with return value "My call time was 3000.".
Executar um método de retorno de chamada quando uma chamada assíncrona for concluída
Se o thread que inicia a chamada assíncrona não precisar ser o thread que processa os resultados, você poderá executar um método de retorno de chamada quando a chamada for concluída. O método de retorno de chamada é executado em um thread ThreadPool.
Para usar um método de retorno de chamada, você deve passar a BeginInvoke
um delegado AsyncCallback que representa o método de retorno de chamada. Você também pode passar um objeto que contém informações a serem usadas pelo método de retorno de chamada. No método de retorno de chamada, você pode converter o IAsyncResult, que é o único parâmetro do método de retorno de chamada, em um objeto AsyncResult. Depois, você pode usar a propriedade AsyncResult.AsyncDelegate para obter o delegado que foi usado para iniciar a chamada para que você possa chamar EndInvoke
.
Observações sobre o exemplo:
O parâmetro
threadId
deTestMethod
é um parâmetroout
([<Out>
ByRef
no Visual Basic), portanto, seu valor de entrada nunca é usado porTestMethod
. Uma variável fictícia é passada para a chamadaBeginInvoke
. Se o parâmetrothreadId
fosse um parâmetroref
(ByRef
no Visual Basic), a variável precisaria ser um campo de nível de classe para que pudesse ser passada paraBeginInvoke
eEndInvoke
.As informações de estado que são passadas para
BeginInvoke
são uma cadeia de caracteres de formato, usada pelo método de retorno de chamada para formatar uma mensagem de saída. Como são passadas como o tipo Object, as informações de estado devem ser convertidas para o tipo correto antes de poderem ser usadas.O retorno de chamada é feito em um thread ThreadPool. Threads ThreadPool são threads em segundo plano, os quais não mantêm o aplicativo em execução se o thread principal terminar. Portanto, o thread principal do exemplo precisa ficar suspenso durante um tempo suficiente para o retorno de chamada ser concluído.
#using <TestMethod.dll>
using namespace System;
using namespace System::Threading;
using namespace System::Runtime::Remoting::Messaging;
using namespace Examples::AdvancedProgramming::AsynchronousOperations;
// The callback method must have the same signature as the
// AsyncCallback delegate.
void CallbackMethod(IAsyncResult^ ar)
{
// Retrieve the delegate.
AsyncResult^ result = (AsyncResult^) ar;
AsyncMethodCaller^ caller = (AsyncMethodCaller^) result->AsyncDelegate;
// Retrieve the format string that was passed as state
// information.
String^ formatString = (String^) ar->AsyncState;
// Define a variable to receive the value of the out parameter.
// If the parameter were ref rather than out then it would have to
// be a class-level field so it could also be passed to BeginInvoke.
int threadId = 0;
// Call EndInvoke to retrieve the results.
String^ returnValue = caller->EndInvoke(threadId, ar);
// Use the format string to format the output message.
Console::WriteLine(formatString, threadId, returnValue);
};
void main()
{
// Create an instance of the test class.
AsyncDemo^ ad = gcnew AsyncDemo();
// Create the delegate.
AsyncMethodCaller^ caller = gcnew AsyncMethodCaller(ad, &AsyncDemo::TestMethod);
// The threadId parameter of TestMethod is an out parameter, so
// its input value is never used by TestMethod. Therefore, a dummy
// variable can be passed to the BeginInvoke call. If the threadId
// parameter were a ref parameter, it would have to be a class-
// level field so that it could be passed to both BeginInvoke and
// EndInvoke.
int dummy = 0;
// Initiate the asynchronous call, passing three seconds (3000 ms)
// for the callDuration parameter of TestMethod; a dummy variable
// for the out parameter (threadId); the callback delegate; and
// state information that can be retrieved by the callback method.
// In this case, the state information is a string that can be used
// to format a console message.
IAsyncResult^ result = caller->BeginInvoke(3000,
dummy,
gcnew AsyncCallback(&CallbackMethod),
"The call executed on thread {0}, with return value \"{1}\".");
Console::WriteLine("The main thread {0} continues to execute...",
Thread::CurrentThread->ManagedThreadId);
// The callback is made on a ThreadPool thread. ThreadPool threads
// are background threads, which do not keep the application running
// if the main thread ends. Comment out the next line to demonstrate
// this.
Thread::Sleep(4000);
Console::WriteLine("The main thread ends.");
}
/* This example produces output similar to the following:
The main thread 1 continues to execute...
Test method begins.
The call executed on thread 3, with return value "My call time was 3000.".
The main thread ends.
*/
using System;
using System.Threading;
using System.Runtime.Remoting.Messaging;
namespace Examples.AdvancedProgramming.AsynchronousOperations
{
public class AsyncMain
{
static void Main()
{
// Create an instance of the test class.
AsyncDemo ad = new AsyncDemo();
// Create the delegate.
AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);
// The threadId parameter of TestMethod is an out parameter, so
// its input value is never used by TestMethod. Therefore, a dummy
// variable can be passed to the BeginInvoke call. If the threadId
// parameter were a ref parameter, it would have to be a class-
// level field so that it could be passed to both BeginInvoke and
// EndInvoke.
int dummy = 0;
// Initiate the asynchronous call, passing three seconds (3000 ms)
// for the callDuration parameter of TestMethod; a dummy variable
// for the out parameter (threadId); the callback delegate; and
// state information that can be retrieved by the callback method.
// In this case, the state information is a string that can be used
// to format a console message.
IAsyncResult result = caller.BeginInvoke(3000,
out dummy,
new AsyncCallback(CallbackMethod),
"The call executed on thread {0}, with return value \"{1}\".");
Console.WriteLine("The main thread {0} continues to execute...",
Thread.CurrentThread.ManagedThreadId);
// The callback is made on a ThreadPool thread. ThreadPool threads
// are background threads, which do not keep the application running
// if the main thread ends. Comment out the next line to demonstrate
// this.
Thread.Sleep(4000);
Console.WriteLine("The main thread ends.");
}
// The callback method must have the same signature as the
// AsyncCallback delegate.
static void CallbackMethod(IAsyncResult ar)
{
// Retrieve the delegate.
AsyncResult result = (AsyncResult) ar;
AsyncMethodCaller caller = (AsyncMethodCaller) result.AsyncDelegate;
// Retrieve the format string that was passed as state
// information.
string formatString = (string) ar.AsyncState;
// Define a variable to receive the value of the out parameter.
// If the parameter were ref rather than out then it would have to
// be a class-level field so it could also be passed to BeginInvoke.
int threadId = 0;
// Call EndInvoke to retrieve the results.
string returnValue = caller.EndInvoke(out threadId, ar);
// Use the format string to format the output message.
Console.WriteLine(formatString, threadId, returnValue);
}
}
}
/* This example produces output similar to the following:
The main thread 1 continues to execute...
Test method begins.
The call executed on thread 3, with return value "My call time was 3000.".
The main thread ends.
*/
Imports System.Threading
Imports System.Runtime.Remoting.Messaging
Namespace Examples.AdvancedProgramming.AsynchronousOperations
Public Class AsyncMain
Shared Sub Main()
' Create an instance of the test class.
Dim ad As New AsyncDemo()
' Create the delegate.
Dim caller As New AsyncMethodCaller(AddressOf ad.TestMethod)
' The threadId parameter of TestMethod is an <Out> parameter, so
' its input value is never used by TestMethod. Therefore, a dummy
' variable can be passed to the BeginInvoke call. If the threadId
' parameter were a ByRef parameter, it would have to be a class-
' level field so that it could be passed to both BeginInvoke and
' EndInvoke.
Dim dummy As Integer = 0
' Initiate the asynchronous call, passing three seconds (3000 ms)
' for the callDuration parameter of TestMethod; a dummy variable
' for the <Out> parameter (threadId); the callback delegate; and
' state information that can be retrieved by the callback method.
' In this case, the state information is a string that can be used
' to format a console message.
Dim result As IAsyncResult = caller.BeginInvoke(3000, _
dummy, _
AddressOf CallbackMethod, _
"The call executed on thread {0}, with return value ""{1}"".")
Console.WriteLine("The main thread {0} continues to execute...", _
Thread.CurrentThread.ManagedThreadId)
' The callback is made on a ThreadPool thread. ThreadPool threads
' are background threads, which do not keep the application running
' if the main thread ends. Comment out the next line to demonstrate
' this.
Thread.Sleep(4000)
Console.WriteLine("The main thread ends.")
End Sub
' The callback method must have the same signature as the
' AsyncCallback delegate.
Shared Sub CallbackMethod(ByVal ar As IAsyncResult)
' Retrieve the delegate.
Dim result As AsyncResult = CType(ar, AsyncResult)
Dim caller As AsyncMethodCaller = CType(result.AsyncDelegate, AsyncMethodCaller)
' Retrieve the format string that was passed as state
' information.
Dim formatString As String = CType(ar.AsyncState, String)
' Define a variable to receive the value of the <Out> parameter.
' If the parameter were ByRef rather than <Out> then it would have to
' be a class-level field so it could also be passed to BeginInvoke.
Dim threadId As Integer = 0
' Call EndInvoke to retrieve the results.
Dim returnValue As String = caller.EndInvoke(threadId, ar)
' Use the format string to format the output message.
Console.WriteLine(formatString, threadId, returnValue)
End Sub
End Class
End Namespace
' This example produces output similar to the following:
'
'The main thread 1 continues to execute...
'Test method begins.
'The call executed on thread 3, with return value "My call time was 3000.".
'The main thread ends.