01.当向一个Web服务器发出一个请求时,如果我们发出请求的代码是同步实现的话,这时候我们的应用程序就会处于等待状态,直到收回一个响应信息为止

class Program
{
static void Main(string[] args)
{
int count=Convert.ToInt32(Console.ReadLine());
if (count==1)
{
long length=AccessWeb();
Console.WriteLine(" 回复的字节长度为:"+length);
}

Console.ReadKey();
}

private static long AccessWeb()
{
MemoryStream content=new MemoryStream();
HttpWebRequest webRequest=WebRequest.Create("https://www.kancloud.cn/wizardforcel/learning-hard-csharp/111510") as HttpWebRequest;
if (webRequest!=null)
{
using (WebResponse response=webRequest.GetResponse())
{
using (Stream responStream=response.GetResponseStream())
{
responStream.CopyTo(content);
}
}
}

return content.Length;
}
}

async和await_异步方法


02.

// 使用C# 5.0中提供的async 和await关键字来定义异步方法

// 从代码中可以看出C#5.0 中定义异步方法就像定义同步方法一样简单。

// 使用async 和await定义异步方法不会创建新线程,

// 它运行在现有线程上执行多个任务.

// 此时不知道大家有没有一个疑问的?在现有线程上(即UI线程上)运行一个耗时的操作时,

// 为什么不会堵塞UI线程的呢?

// 这个问题的答案就是 当编译器看到await关键字时,线程会

static void Main(string[] args)
{
Console.WriteLine("主线程ID:" + Thread.GetCurrentProcessorId());
GetValue();
Console.WriteLine("666");
Console.ReadKey();
}


static async Task GetValue()
{
await Task.Run(() =>
{
Console.WriteLine("当前线程ID:"+Thread.GetCurrentProcessorId());
Thread.Sleep(2000);
for (int i = 0; i < 5; i++)
{
Console.WriteLine( String.Format("From task : {0}", i));
}
});
Console.WriteLine("Task End");
}

async和await_c#_02


03

.异步方法的返回值类型有三种:void,Task 和 Task。

使用 async 关键字修饰方法签名,表示该方法为异步方法。

在异步方法内使用 await 关键字来等待一个「可等待」类型,实现异步。

遇到 await 关键字时,控制权立即返回给调用者,同时等待 await 语句所指代的异步方法的结束,当方法执行完毕返回结果时,接着执行 await 语句后面的代码。