C# async await 例子
private static async void Worker()
{
Console.Write("main thread id is :{0}",Thread.CurrentThread.ManagedThreadId);
while(true)
{
//Console.ReadKey();
string s = await myAsync();//注意虽然返回的是task<string>但是可以用string 去接收。
Console.WriteLine(s);
}
}
//这个也是单一职责的体现、一个函数只做一件事。就是说返回task<T>的函数只是负责用一个新的线程去完成逻辑。然后再用一个async 函数去调用它。
private static Task<string> myAsync()
{
Task<string> t = new Task<string>(() =>
{
DateTime dt = DateTime.Now;
Thread.Sleep(4000);
return string.Format("inner thread is :{0} start time is :{1} end time is :{2}", Thread.CurrentThread.ManagedThreadId,dt,DateTime.Now);
});
t.Start();
return t;
}