Learn how to start execution of a method and continue with other tasks while the method runs on a separate thread. After the method completes, you need to retrieve the method’s return value.
Declare a delegate with the same signature as the method you want to execute.
Create an instance of the delegate that references the method.
Call the BeginInvoke method of the delegate instance to start executing your method.
Use the EndInvoke method to determine the method’s status as well as obtain the method’s return value if complete.
The following code demonstrates how to use the asynchronous execution pattern. It uses a delegate named AsyncDelegate to execute a method named GetData Method asynchronously.
Declare a delegate with the same signature as the method you want to execute.
Create an instance of the delegate that references the method.
Call the BeginInvoke method of the delegate instance to start executing your method.
Use the EndInvoke method to determine the method’s status as well as obtain the method’s return value if complete.
The following code demonstrates how to use the asynchronous execution pattern. It uses a delegate named AsyncDelegate to execute a method named GetData Method asynchronously.
using System;
using System.Threading;
namespace Thread_Asynchronous_Demo
{
class Program
{
public static void Main(string[] args)
{
// Invoke GetData Method asynchronously. Pass null for both the
// callback delegate and the asynchronous state object.
AsyncDelegate longRunningMethod = GetData;
IAsyncResult asyncResult = longRunningMethod.BeginInvoke("Hi, thread", null, null);
// Perform other processing.
for (int count = 0; count < 5; count++)
{
Console.WriteLine("Thread " + count);
Thread.Sleep(2000);
}
// Obtain the GetData method data for the asynchronous method.
string result = longRunningMethod.EndInvoke(asyncResult);
// Display GetData method data information.
Console.WriteLine("GetData return Message :" + result + ". Press Enter.");
Console.ReadLine();
}
// A delegate that allows you to perform asynchronous execution of
// GetData Method.
public delegate string AsyncDelegate(string Message);
// A simulated long-running method.
public static string GetData(string Message)
{
Thread.Sleep(TimeSpan.FromSeconds(2));
return Message;
}
}
}
Output
0 comments:
Post a Comment