等待和异步在同一行 [英] Await and Async in same line

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

问题描述

我了解异步工作,以及如何使用JavaScript的承诺相比,但林不知道怎么样下方的行能有什么好处

I understand how async works and how it compares with the javascript promises, but im not sure how a line like the below could have any benefit

IdentityResult result = await UserManager.CreateAsync(user, model.password);

由于我们正在创建一个异步调用,并立即线程上等待,这样如下不会直到异步调用执行的行调用完成。

since we're creating an async call and immediately waiting on the thread so the lines that follows won't be executed till the Async call calls complete.

推荐答案

这样做的好处是,如果该操作是真正的异步然后在某个时候调用线程将被释放做其他的工作在你的应用程序,而不是被同步阻塞。

The benefit is that if that operation is truly asynchronous then at some point the calling thread will be freed to do other work in your application instead of being blocked synchronously.

这是一种用法带来了更高的可扩展性。

That kind of usage brings higher scalability.

您还在等待,直到在继续之前的操作完成。异步方法不神奇运行得更快,但他们可能使用更少的资源,你通常可以同时运行多个的。

You're still waiting until the operation completes before moving on. Async methods don't magically run faster, but they do potentially use less resources and you can usually run multiple ones concurrently.

如果我们想象 CreateAsync 是这样的:

If we imagine that CreateAsync looks like this:

async Task<IdentityResult> CreateAsync()
{
    // do something
    await Task.Delay(1000);
    // do something else
}

然后,在等待Task.Delay(1000)你腾出一个线程等待的坚持着它的第二个异步代替。该线程可以在执行过程中的其他CPU的操作,避免了上下文切换。

Then at await Task.Delay(1000) you free up a thread and wait asynchronously instead of holding on to it for a second. That thread can execute other CPU operations in your process and avoid a context switch.

如果 CreateAsync 实施正确的然后有一些实际的异步操作而不是 Task.Delay

If CreateAsync is implemented right then there is some actual asynchronous operation instead of that Task.Delay

这篇关于等待和异步在同一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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