ASP.NET Core管道多线程 [英] ASP.NET Core pipeline multithreading
问题描述
ASP.NET Core管道是否通过多线程处理请求? 如果可以,如何配置线程数?而且,单例服务是否应该是线程安全的?
Does ASP.NET Core pipeline handle requests by multithreading? If it does, how do you configure the number of threads? And also, should singleton services be thread safe?
推荐答案
The first question was already answered in the comment above (look into KestrelServerOptions)
Regarding thread safetly, the answer is in the documentation:
单生命周期服务是在首次请求它们时创建的(如果在其中指定实例,则在运行ConfigureServices时),然后每个后续请求将使用相同的实例.如果您的应用程序要求单例行为,则建议允许服务容器管理服务的生命周期,而不是自己在类中实现单例设计模式并管理对象的生命周期.
Singleton lifetime services are created the first time they are requested (or when ConfigureServices is run if you specify an instance there) and then every subsequent request will use the same instance. If your application requires singleton behavior, allowing the services container to manage the service's lifetime is recommended instead of implementing the singleton design pattern and managing your object's lifetime in the class yourself.
这意味着对服务的所有请求都拉同一个对象,这意味着没有每个线程的对象,因此也就没有线程安全性.
That means all requests for the service pull the same object, which means no per-thread objects, and thus no thread safety.
线程安全
Singleton服务必须是线程安全的.如果单例服务依赖于临时服务,则根据单例的使用方式,临时服务可能还需要具有线程安全性.
Singleton services need to be thread safe. If a singleton service has a dependency on a transient service, the transient service may also need to be thread safe depending how it’s used by the singleton.
还不清楚.由于不是按线程创建对象,因此默认情况下它们不是线程安全的(尽管可能设计了某些服务).
Coudn't be more clear. Since the objects are not created per thread, they are not thread safe by default (though it's possible some services are designed to be).
这篇关于ASP.NET Core管道多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!