gpt4 book ai didi

asp.net-mvc - 等待Task.Delay;真的使 Web 服务器能够处理更多的并发请求吗?

转载 作者:行者123 更新时间:2023-12-01 08:58:30 25 4
gpt4 key购买 nike

来自 使用 .Net 进行专业异步编程:

    for (int nTry = 0; nTry < 3; nTry++)
{
try
{
AttemptOperation();
break;
}
catch (OperationFailedException) { }
Thread.Sleep(2000);
}

While sleeping, the thread doesn’t consume any CPU-based resources, but the fact that the thread is alive means that it is still consuming memory resources. On a desktop application this is probably no big deal, but on a server application, having lots of threads sleeping is not ideal because if more work arrives on the server, it may have to spin up more threads, increasing memory pressure and adding additional resources for the OS to manage.

Ideally, instead of putting the thread to sleep, you would like to simply give it up, allowing the thread to be free to serve other requests. When you are ready to continue using CPU resources again, you can obtain a thread ( not necessarily the same one ) and continue processing. You can solve this problem by not putting the thread to sleep, but rather using await on a Task that is deemed to be completed in a given period.

    for (int nTry = 0; nTry < 3; nTry++)
{
try
{
AttemptOperation();
break;
}
catch (OperationFailedException) { }
await Task.Delay(2000);
}

我不遵循作者的推理。虽然调用 await Task.Delay 确实会释放这个线程(它正在处理一个请求),但由 Task.Delay 创建的任务也会占用一些其他线程也是真的要运行的线程。那么这段代码真的可以让服务器处理更多的并发请求还是文本错误?!

最佳答案

Task.Delay 不占用其他线程。它给你一个没有阻塞的任务。它启动一个计时器,在其回调中完成该任务。计时器在等待时不使用任何线程。

延迟或 IO 等异步操作只是将工作推送到不同的线程,这是一个常见的神话。他们不。他们使用操作系统工具在操作进行时真正使用零线程。 (他们显然需要使用一些线程来启动和完成操作。)

如果 async 只是将工作推送到不同的线程,那么它几乎是无用的。它的值(value)只是让用户界面在客户端应用程序中保持响应。在服务器上它只会造成伤害。不是这样的。

异步 ​​IO 的值(value)在于减少内存使用(更少的线程堆栈)、上下文切换和线程池利用率。

您发布的代码的异步版本可以扩展到数以万计的并发请求(如果您适当增加 ASP.NET 限制,这是一个简单的 web.config 更改),内存使用量很小。

关于asp.net-mvc - 等待Task.Delay;真的使 Web 服务器能够处理更多的并发请求吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23939125/

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