C# Async,Await简单理解(应用层次)


这里我就不给大家去研究这两上下文关键字的il实现了,感兴趣的朋友可以自己去用ildasm分析一下。
我写这篇文章只是想强调微软官方文档上写的一点:

 

async和await并没有开辟新的线程,我们来分别执行一下io密集型和cpu密集型代码

 

static void Main(string[] args){
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
GetUrlContentLengthAsync();
stopwatch.Stop();
Console.WriteLine("async,await时间: " + stopwatch.ElapsedMilliseconds);

Stopwatch stopwatch1 = new Stopwatch();
stopwatch1.Start();
GetUrlContentLength();
stopwatch1.Stop();
Console.WriteLine("非async,await时间: " + stopwatch1.ElapsedMilliseconds);
}

public async static Task<int> GetUrlContentLength()
{
var client = new HttpClient();

string getStringTask =
client.GetStringAsync("https://learn.microsoft.com/dotnet").ToString();

DoIndependentWork();

string contents = getStringTask;

return contents.Length;
}

public async static Task<int> GetUrlContentLengthAsync()
{
var client = new HttpClient();

Task<string> getStringTask =
client.GetStringAsync("https://learn.microsoft.com/dotnet");

DoIndependentWork();

string contents = await getStringTask;

return contents.Length;
}

static void DoIndependentWork()
{
Console.WriteLine("Working...");
}

运行结果:

 

这是io密集型,就是微软官方文档的示例代码
为什么用了这个反而更慢?我理解的是因为存在上下文状态的切换。
可能我这样说不是很直观,我推荐阅读微软原文档:
https://learn.microsoft.com/zh-cn/dotnet/csharp/asynchronous-programming/task-asynchronous-programming-model?source=recommendations

我们再来看一个cpu密集型操作:

static void Main(string[] args){
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
GetnumAsync();
stopwatch.Stop();
Console.WriteLine("async,await时间: " + stopwatch.ElapsedMilliseconds);

Stopwatch stopwatch1 = new Stopwatch();
stopwatch1.Start();
Getnum();
stopwatch1.Stop();
Console.WriteLine("主线程时间: " + stopwatch1.ElapsedMilliseconds);
}
public async static Task<int> GetnumAsync()
{
int num = 0;
await Task.Run(() =>
{
for (int i = 0; i < 100000000; i++)
{
num += i;
}
});

return num;
}

public static int Getnum()
{
Stopwatch stopwatch1 = new Stopwatch();
stopwatch1.Start();
int num = 0;
for (int i = 0; i < 100000000; i++)
{
num += i;
}
stopwatch1.Stop();
Console.WriteLine("子线程时间: " + stopwatch1.ElapsedMilliseconds);


return num;
}

  


运行结果如下:

 

此时,反而开辟了新线程,用时会更长,为什么呢?很简单,因为线程间的切换是需要资源的。
希望大家亲手实践一下我提供的这两例子,加深自己的映像。若有不对,请指正。

posted @ 2023-04-18 16:48  苏州の酱醋茶  阅读(145)  评论(2编辑  收藏  举报