且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用异步和等待关键字的好处

更新时间:2023-02-24 21:19:10

假设您有一个边界检查点.每辆车都可以一次通过,让海关检查一下自己的车,看看他们是否没有走私比利时的巧克力.

Say you have a single border checkpoint. Each car can pass it one-by-one to have customs take a look at their car to see if they're not smuggling any Belgian chocolate.

现在,假设您已经排在大众甲壳虫的行列中,那么在成为24轮怪兽卡车之前,您几乎无法适应.您现在已经在这个庞然大物后面呆了很长时间,直到海关在对它进行全面搜索之后,他们才可以继续向您求婚,他们基本上只需要轻拍一下就可以告诉您,您很好.

Now assume that you are in line in your Volkswagen Beetle where you can barely fit in and before you is a 24-wheel monstertruck. You are now stuck behind this behemoth for a long time until customs are done searching through it all before they can move on to you who they basically just have to pat down to tell you you're good to go.

为了对抗这种效率,我们在边境巡逻的好朋友有了一个主意,并安装了第二个检查站.现在他们可以传给两倍的人数,而您只需接一个,而不用等到怪物卡车后面!

In order to combat this efficiency, our good friends at the border patrol have an idea and install a second checkpoint. Now they can pass in twice as many people and you can just take that one instead of waiting behind the monstertruck!

问题解决了吧?不完全是.他们忘记创建通往该检查站的第二条道路,因此所有交通仍必须经过单个车道,从而导致卡车仍然挡住了甲壳虫.

Problem solved, right? Not exactly. They forgot to create a second road that leads to that checkpoint so all traffic still has to go over the single lane, resulting in the truck still blocking the Beetle.

这与您的代码有何关系?非常简单:您正在做同样的事情.

How does this relate to your code? Very easy: you're doing the same.

创建新的Task时,实际上是创建了第二个检查点.但是,当您现在使用.Wait()同步阻止它时,您将迫使所有人都走这条路.

When you create a new Task you essentially create that second checkpoint. However when you now synchronously block it using .Wait(), you are forcing everyone to take that single road.

在第二个示例中,您使用await创建第二条道路,并允许您的汽车与卡车同时处理.

In the second example you use await which creates that second road and allows your car to be handled simultaneously with the truck.