简体   繁体   English

异步方法并等待

[英]Async methods and await

I have question regarding the way of async programming and await. 我对异步编程和等待的方式有疑问。 I understand that when the method is async you can use await to wait for execution of the particular code, but I would like to understand a bit more. 我知道当方法异步时,您可以使用await来等待特定代码的执行,但是我想了解更多一点。

So I have a specific question: 所以我有一个具体的问题:

Imagine I have a method: 想象一下我有一个方法:

public async void Starter()
{
    string username = await GetUserNameFromDBAsync();
    bool updated = await UpdateUserTown();
}

public async static Task<string> GetUserNameFromDBAsync()
{
    using(DBContext context = new DBContext())
    {
       return await context.User.FindByIdAsync(currentid).Name;
    }
}

public async static Task<bool> UpdateUserTown()
{
    using(DBContext context = new DBContext())
    {
       User user = await context.User.FindUserByIDAsync(currentid);
       user.Town="New Town";
       try
       {
          context.SaveChangesAsync();
       }
       catch(Exception ex)
       {return false}
       return true;
    }
}

Ok doing this code, although I use everywhere async, but all the time I have to do await ... so basically for performance it will be exactly the same as if I would remove all this asyncs and awaits and do it without ... 好的,执行这段代码,尽管我在所有地方都使用async,但是一直以来我都需要做await ...因此,从性能上讲,它和我将删除所有这些asyncs和awaits并且不进行操作而完全相同...

Or maybe I miss something? 也许我想念什么?

In desktop applications, async isn't about performance, it's about responsiveness. 在桌面应用程序中, async与性能无关,而与响应能力有关。 You don't want your application's GUI to freeze up while performing long-running, I/O bound operations. 在执行长时间运行的,受I / O约束的操作时,您不希望冻结应用程序的GUI。 The usual way of accomplishing that is via threading, but threads are expensive and difficult to properly synchronize, and they're overkill if all you want to do is keep your UI responsive while you're pulling down data from a web service. 通常的实现方法是通过线程进行,但是线程昂贵且难以正确同步,如果您要做的只是在从Web服务中提取数据时保持UI响应能力,那么它们就显得过高了。

In web applications, having an async controller lets your website process more requests concurrently, because the thread your controller is running on can go back into the thread pool and serve more requests while it's waiting for your await s to complete. 在Web应用程序中,拥有一个async控制器可以使您的网站同时处理更多请求,因为正在运行控制器的线程可以返回线程池并在等待您的await完成时处理更多请求。

Also, a note on your code: You should never have something marked as async void unless it's an event handler. 另外,关于代码的注释:除非它是事件处理程序,否则永远不要将其标记为async void You can't await an async void method, and you can't catch exceptions that occur. 您无法await async void方法,也无法捕获发生的异常。 Instead, if your method doesn't return anything, use async Task . 相反,如果您的方法未返回任何内容,请使用async Task

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM