gpt4 book ai didi

c# - 当并非所有代码部分都是异步时,异步 Web 服务有什么好处

转载 作者:太空狗 更新时间:2023-10-29 18:27:11 24 4
gpt4 key购买 nike

我想知道如果您的代码并非所有部分都是异步的,那么使用异步 http 请求会带来多少好处。

让我们考虑以下场景:1) 异步 http 请求阻塞同步数据库调用,以及 2) 同步 http 请求等待异步数据库调用。

1) Web Api 支持异步操作方法,但是如果我在处理请求时执行同步数据库调用,那么线程会阻塞调用,我将无法获得异步可以给我带来的更好的线程经济性的好处,或者什么?

2) 如果我有一个等待异步数据库调用的同步 ServiceStack 服务调用,那么会发生什么?我假设一个线程被保留用于处理整个同步 http 请求,当这个线程等待异步调用时它仍然被保留给 web 请求或者什么?

基本上我的问题可以归结为:如果不是所有的 IO 调用都是异步的,是否有任何理由使用异步?

最佳答案

在服务器端,部分异步解决方案通常没有任何好处。

1) Web Api supports async action methods, but if I do a sync database call when handling the request, then the thread blocks on the call, and I will not get the benefits of better thread economy that async could give me or what?

正确。一旦执行同步(阻塞)数据库调用,您就会在该调用期间占用一个线程。因此,您从 async 中获得的好处不适用。

2) If I have a synchronous ServiceStack service call that awaits an async database call, then what happens? I assume a thread is reserved for handling the entire sync http request, and when this thread awaits an async call then it is still reserved to the web request or what ?

这与同步数据库调用相同。在幕后,同步数据库调用异步执行实际调用,然后阻塞调用线程直到完成。因此,在调用期间您仍然有一个线程被阻塞,并且您没有获得任何 async 好处。

Basicallly my question can be boiled down to this: Is there any reason to use async if not all IO calls are async?

还有一些更晦涩的场景。您可以使用 Task.WhenAll 进行有限类型的并发,使用 async 比使用其他形式的异步并发要容易得多。但如果您没有完全 async 堆栈,这是我能想到的唯一好处。

关于c# - 当并非所有代码部分都是异步时,异步 Web 服务有什么好处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16840878/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com