C# async await 学习笔记1

时间:2022-06-29 12:12:05

由于我的开发工具为vs.net 2010(.net 4.0),需先做以下两步才能进行:

1.下载并安装Async CTP (http://www.microsoft.com/en-us/download/details.aspx?id=9983)

2.添加AsyncCtpLibrary.dll的引用,我用的是win7在(C:\Users\Administrator\Documents\Microsoft Visual Studio Async CTP\Samples)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading; namespace ConsoleApplication1
{
class Program
{
static Task<string> LongTimeTask()
{
Console.WriteLine("LongTimeTask开始:" + DateTime.Now.ToString() + " ThreadId:" + Thread.CurrentThread.ManagedThreadId); Task<string> task = new Task<string>(() => { Thread.Sleep(); return "这是任务返回值"; });
task.Start(); Console.WriteLine("LongTimeTask结束:" + DateTime.Now.ToString()); return task;
} static async void AsyncCall()
{
Console.WriteLine("AsyncCall开始:" + DateTime.Now.ToString() + " ThreadId:" + Thread.CurrentThread.ManagedThreadId); string result = await LongTimeTask(); //await调用的方法需要返回Task或Task<T>,且调用await所在的方法要有async关键字
Console.WriteLine("AsyncCall:" + result); Console.WriteLine("AsyncCall结束:" + DateTime.Now.ToString());
} static void Main(string[] args)
{
Console.WriteLine("Main开始:" + DateTime.Now.ToString() + " ThreadId:" +Thread.CurrentThread.ManagedThreadId);
AsyncCall();
Console.WriteLine("Main结束:" + DateTime.Now.ToString());
Console.ReadLine();
}
}
}

运行结果:

C# async await 学习笔记1

不知大家注意到,里面的ThreadId是一致的。

需要注意的是,并不是加了async,就是异步了(而是得里面有调用await方法),例如,下面其实是同步执行的

 static async void SyncCall()
{
Thread.Sleep();
} static void Main(string[] args)
{
Console.WriteLine("Main开始:" + DateTime.Now.ToString());
// AsyncCall();
SyncCall();
Console.WriteLine("Main结束:" + DateTime.Now.ToString()); Console.ReadLine();
}

C# async await 学习笔记1