简体   繁体   English

异步并等待调用者不是异步但调用方法是异步的地方

[英]Async and await where caller is not async but called methods are

Can anyone explain to me what would happen in the following situation: 任何人都可以向我解释在以下情况下会发生什么:

public int? getValue()
{
    return GetIntValue().Result;
}

public async Task<int?> GetIntValue()
{
    return await getId();
}

public async Task<int?> getId()
{
    return (await Context.Users.FirstOrDefaultAsync())?.AssignedUserId;
}

and if this situation is any different: 如果这种情况有所不同:

public int? getValue()
{
    return getId().Result;
}

Basically, I am wondering if the await here will cause the execution to continue before the result has been returned in either (or both cases), and if they are different, why are they different? 基本上,我想知道这里的等待是否会导致在两种(或两种情况)返回结果之前继续执行,并且如果它们不同,为什么它们不同?

This getId().Result; getId().Result; is a blocking call that possibly would result in a deadlock scenario. 是一个阻塞调用,可能会导致死锁。 The current thread of execution would block until the function that is called to return. 当前执行线程将阻塞,直到调用返回的函数为止。

On the other hand using the async/await approach you will not block. 另一方面,使用async/await方法将不会阻塞。 The thread that process this call, would stop and would be available for processing another call. 处理该调用的线程将停止并且可用于处理另一个调用。 Then when your function call would be completed, the result would be processed by another thread of the thread pool. 然后,当函数调用完成时,结果将由线程池中的另一个线程处理。

Now how the above blocking call would affect your application it depends on the type of your application. 现在,上面的阻塞调用将如何影响您的应用程序,这取决于您的应用程序类型。 For instance if we are talking about a Windows Forms application or a WPF application and this code would be executed on the UI thread your form would freeze until this call being completed. 例如,如果我们谈论的是Windows Forms应用程序或WPF应用程序,并且此代码将在UI线程上执行,则您的表单将冻结,直到完成此调用为止。 On the other hand if this is a ASP.NET application and you have many requests hitting the server this can result in an exhaustion of the ASP.NET threads, whose purpose is to process the requests that server receives. 另一方面,如果这是一个ASP.NET应用程序,并且您有许多请求到达服务器,则可能导致ASP.NET线程用尽,其目的是处理服务器接收到的请求。 Apparently, this would result in an application that doesn't respond to new requests, until the some of the requests server received get their response. 显然,这将导致应用程序不响应新请求,直到收到的某些请求服务器获得响应为止。

Regarding the deadlock scenario, please have a look at this question and especially at the first answer. 关于死锁情况,请查看此问题 ,尤其是第一个答案。 At this you will find a link to an excellent article on this topic Don't Block on Async Code . 在这里,您将找到有关此主题的出色文章的链接,该文章请勿阻塞异步代码

它将导致相同的结果,两者都将等待,直到检索到用户为止,因此getValue()方法将返回value并且不会返回null。

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

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