C# 中的Async 和 Await
基本用法
注意 异步方法 必须要有 async 标记,内部 异步 对象 也要有 await 标记
static void Main(string[] args)
{
Console.OutputEncoding = Encoding.UTF8;
//callMethod();
Method1();
Console.WriteLine("=================");
Console.ReadKey();
}
public static async void Method1()
{
int count = 0;
var t= Task.Run(() => // 开始异步
{
//for (int i = 0; i < 100; i++)
//{
// Thread.Sleep(10);
// Console.WriteLine(" Method 1");
// count += 1;
//}
count = 10;
Console.WriteLine("Method1");
return count;
});
await t; // 主线程继续,没有 await ,主线程会继续阻塞
Thread.Sleep(5000);
Console.WriteLine("end");
}

浙公网安备 33010602011771号