与MVC中的异步等待混淆 [英] Confused with async await in MVC

查看:84
本文介绍了与MVC中的异步等待混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天问了一个问题如何在不等待长时间运行的过程的情况下运行方法,我得到了很好的答案,而ajax解决了我的问题. 但是现在我的问题是,为什么我仍然应该使用异步等待关键字?

I asked a question today How can I run a method without waiting for long running process and I got a good answer and ajax solved my problem. But now my question is why should I still use async await keywords?

public async Task<ActionResult> DoSomeAsyncStuff()
{
    var model = new MyModel();
    await Task.Delay(20000);//My long-running process is getting data from an API with "HttpWebRequest".

    model.Name = "Something";
    //Assigning other model properties

    return PartialView("_InnerView", model);
}

异步await关键字是否可以避免阻止UI?但是在网络上,与WinForms不同,在网络上我看不到任何阻塞的UI.即使没有async await关键字,上面的代码和ajax也可以很好地工作.所以有人可以解释为什么我应该使用它们,它们的用法是什么?

Isn't the async await keywords to avoid blocking UI? But in the web I can't see any blocking UI in my case in the web unlike WinForms. The above code and ajax works great even without async await keywords. So someone please can explain why should I use them and what is their usages?

推荐答案

请求异步的原因是允许单个线程处理多个请求,而不是有关UI的任何请求(服务器实际上没有毕竟,它只是以某种方式返回文件或数据).如果该方法是同步的,则在您等待时将阻止处理此请求的线程,并且如果您一次接收到大量请求,则可以快速增加使用的线程数.由于线程确实会带来一些开销,因此可能会对服务器的性能产生负面影响.

The reason requests are async is to allow for multiple requests to be handled by a single thread, rather than anything regarding a UI (A server doesn't really have a UI after all, it just returns files or data in some fashion). If the method was synchronous, the thread handling this request would be blocked while you wait, and if you're receiving a large number of requests at once, you can quickly rack up the number of threads you use. As threads do come with some overhead, this can negatively impact the performance of your server as a result.

通过使用async/await,此线程被释放以同时处理另一个请求,这比仅仅阻塞一个线程要快得多,效率也要高得多.在您的示例中,一个线程可以同时处理DoSomeAsyncStuff()的多个调用-当它命中await Task.Delay(20000);时,可以从先前命中的await或从方法开始处继续处理另一个请求.

By using async/await, this thread is freed to handle another request at the same time which is both much quicker and much more efficient than just blocking a thread for a while. In your example, one thread can handle multiple calls of DoSomeAsyncStuff() simultaneously - When it hits await Task.Delay(20000);, another request can then be handled either resuming from a previously hit await or from the start of the method.

这篇关于与MVC中的异步等待混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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