using System;
using System.Threading.Tasks;
class Program {
static async Task Main() {
Console.WriteLine("Start the async method");
// 调用异步方法,并等待执行完毕
string result = await DoSomethingAsync();
Console.WriteLine($"async method returned {result}");
Console.WriteLine("Finish the async method");
}
static async Task<string> DoSomethingAsync() {
Console.WriteLine("Start to do something async");
await Task.Delay(1000); // 等待1秒钟后返回结果
Console.WriteLine("Doing after the delay...");
await Task.Delay(2000); // 等待2秒钟,注意这里不能使用 Task.Run,因为不是 CPU 密集型操作
Console.WriteLine("Doing after the second delay...");
return "Operation completed!";
}
}
c#异步详细方法
最新推荐文章于 2024-07-20 17:30:58 发布