using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace AsyncMethod
{
class Program
{
static void Main(string[] args)
{
//async method keyword: await async
Console.WriteLine($"Main() start code line:{Thread.CurrentThread.ManagedThreadId}");
//调用返回值void的异步方法,调用不能用await关键字
AsyncMethod();
Console.WriteLine($"Main() end code line:{Thread.CurrentThread.ManagedThreadId}");
Console.ReadKey();
}
/// <summary>
/// 返回值为void的异步方法,如果异步方法内没有await关键字,则这个异步方法的调用与普通的同步方法没有区别
/// </summary>
static async void AsyncMethod()
{
//调用线程进入异步方法执行代码
Console.WriteLine($"async method start code line:{Thread.CurrentThread.ManagedThreadId}");
//调用线程遇到异步方法第一个await,返回调用线程继续执行异步方法下面的代码,task由新的线程执行
await Task.Run(() =>
{
Thread.Sleep(100);
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(1000);
});
Console.WriteLine($"code after void async method await:{Thread.CurrentThread.ManagedThreadId}");
//调用的异步方法AsyncMethodReturnTask,调用前加关键字await
//在方法内部第一个await关键字时,调用线程终止,await的Task代码及后面的代码,由新分配的线程执行
await AsyncMethodReturnTask();
//异步方法await后面的语句,等Task代码执行结束后,由新开的task的线程继续执行
Console.WriteLine($"async method end code line:{Thread.CurrentThread.ManagedThreadId}");
}
/// <summary>
/// 返回值为Task的异步方法
/// </summary>
/// <returns></returns>
static async Task AsyncMethodReturnTask()
{
Console.WriteLine($"AsyncMethodReturnTask start:{Thread.CurrentThread.ManagedThreadId}");
//public static Task<TResult> Run<TResult>(Func<TResult> function);
int result = await Task.Run(() =>
{
Thread.Sleep(2000);
return 666;
});
Console.WriteLine($"AsyncMethodReturnTask end:{Thread.CurrentThread.ManagedThreadId}");
}
}
}
代码执行结果如下》》》