How to implement asynchronous method calling in C#?
In C#, asynchronous method calls can be implemented in several ways.
- Use the keywords async and await: add the async keyword before the method declaration, and then use the await keyword inside the method where asynchronous execution is needed to wait for the completion of the asynchronous operation. For example:
public async Task<string> GetResultAsync()
{
// 异步操作
await Task.Delay(1000);
return "异步调用完成";
}
- You can utilize the Task.Run method to execute a method on a new thread and receive a Task object. You can use Task.Result to retrieve the return value of an asynchronous method. For example:
public static async Task<string> GetResultAsync()
{
return await Task.Run(() =>
{
// 异步操作
Thread.Sleep(1000);
return "异步调用完成";
});
}
- Using delegates and the BeginInvoke method: One can utilize delegates and the BeginInvoke method to asynchronously call methods, and retrieve the return value of the method using the EndInvoke method. For example:
public delegate string MyDelegate();
public static string GetResult()
{
// 同步操作
Thread.Sleep(1000);
return "异步调用完成";
}
public static void AsyncCallback(IAsyncResult ar)
{
MyDelegate del = (MyDelegate)((AsyncResult)ar).AsyncDelegate;
string result = del.EndInvoke(ar);
Console.WriteLine(result);
}
public static void Main(string[] args)
{
MyDelegate del = new MyDelegate(GetResult);
del.BeginInvoke(new AsyncCallback(AsyncCallback), del);
// 等待异步调用完成
Console.ReadLine();
}
The above are several common ways to implement asynchronous method calls, and you can choose the suitable method based on your specific needs.