使用 async 和 await 关键字的好处 [英] Benefits of using async and await keywords

查看:55
本文介绍了使用 async 和 await 关键字的好处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是在 C# 中使用异步方法的新手.我读过这些关键字 asyncawait 通过异步一些方法来帮助使程序更具响应性.我有这个片段:

I'm new in the use of asynchronous methods in C#. I have read that these keywords async and await help to make the program more responsive by asynchronizing some methods. I have this snippet :

第一种方式

    public static void Main()
    {
        Console.WriteLine("Hello!! welcome to task application");
        Console.ReadKey();
        Task<string> ourtask = Task.Factory.StartNew<string>(() =>
        {
            return "Good Job";
        });
        ourtask.Wait();
        Console.WriteLine(ourtask.Result);
        Console.ReadKey();
    }

第二种方式

 public static void Main()
        {
            Launch();
        }
        public static async void Launch()
        {
            Console.WriteLine("Hello!! welcome to task application");
            Console.ReadKey();
            Console.WriteLine(await GetMessage());
            Console.ReadKey();
        }

        public static Task<string> GetMessage()
        {
            return Task.Factory.StartNew<string>(() =>
                {
                    return "Good Job";
                });
        }

我需要知道:

  1. 这两种实现之间有区别吗(在并行的概念上)?

  1. Is there a difference between the two implementations (in the concept of parallelism)?

如果我可以创建一个任务并等待它完成,那么使用 asyncawait 关键字有什么好处?

What are the benefits of using async and await keywords if I can just create a task and wait for it to finish?

推荐答案

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

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.

这篇关于使用 async 和 await 关键字的好处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆