c#-异步编程-异步模式
using System;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp19
{
class Program
{
private const string url = "http://www.baidu.com";
static async Task Main(string[] args)
{
Console.WriteLine("Hello World!");
//fun();
//fun2();
//fun3();
await fun4();
Thread.Sleep(8000);
}
// 同步调用
static void fun() {
using (var client = new WebClient()) {
string content = client.DownloadString(url);
Console.WriteLine(content.Substring(0,100));
}
Console.WriteLine();
}
// 异步模式
static void fun2() {
WebRequest r = WebRequest.Create(url);
IAsyncResult result = r.BeginGetResponse(ReadResponse, null);
void ReadResponse(IAsyncResult ar) {
using (WebResponse response = r.EndGetResponse(ar)) {
Stream strenm = response.GetResponseStream();
var reader = new StreamReader(strenm);
string content = reader.ReadToEnd();
Console.WriteLine(content.Substring(0, 100));
Console.WriteLine();
}
}
}
// 事件模式
static void fun3() {
using (var client = new WebClient()) {
client.DownloadStringCompleted += (sender, e) =>
{
Console.WriteLine(e.Result.Substring(0, 100));
};
client.DownloadStringAsync(new Uri(url));
Console.WriteLine();
}
}
// 基于任务的异步模式
static async Task fun4() {
using (var client = new WebClient()) {
string content = await client.DownloadStringTaskAsync(url);
Console.WriteLine(content.Substring(1, 100));
Console.WriteLine();
}
}
}
}
二 同步上下文
使用 async 和 await 关键字之后,一般就会到了当前的线程,通常是ui线程,但是如果执行玩之后,不需要进行uic操作,也可以不进入ui线程,直接在原来的线程,出来。但需要金属设置,因为默认的设置 是会跳转到uix线程的。
continueOnCapturedContext设置为fase就表示不用切换到同步上下文,这样执行的会更快一点。