简体   繁体   English

了解asp.net中的线程以及如何分配服务器内存

[英]Understanding threading in asp.net and how server memory is allocated

If for instance, 3 requests are made to the server, does that mean 3 instances of the web application are put into memory? 例如,如果向服务器发出3个请求,是否意味着将Web应用程序的3个实例放入内存?

What if you used a locked singleton or cached a class so each time it checks to see if the object exists or not and creates the object if it doesn't exist, does that mean that the object is cached for each request? 如果您使用锁定的单例或缓存了一个类,以便每次它检查该对象是否存在并创建该对象(如果不存在)时该怎么办,是否意味着该对象针对每个请求进行了缓存? or is it cached once and reused for each request? 还是将其缓存一次并为每个请求重用?

If I locked a singleton, does that mean The object using the singleton is created once and each request uses the same object? 如果我锁定了一个单例,这是否意味着使用该单例的对象被创建一次,并且每个请求都使用相同的对象? or does it mean the object is created using the singleton for each request but is not created again by the same thread? 还是意味着该对象是针对每个请求使用单例创建的,而不是由同一线程再次创建的?

If I used System.Web.HttpRuntime.Cache["key"]; 如果我使用System.Web.HttpRuntime.Cache["key"]; to cache a 1 mb object and 10 requests are made, am I using up 10 mb's of memory on the server? 缓存一个1 mb的对象并发出10个请求,我是否在服务器上用完了10 mb的内存? if I created a new object using a singleton... what occurs in terms of threading and memory allocation? 如果我使用单例创建了一个新对象...就线程和内存分配而言会发生什么?

In IIS an AppDomain is created for each Application and will share a process with other applications in the same AppPool. 在IIS中,将为每个应用程序创建一个AppDomain,并将与同一AppPool中的其他应用程序共享一个进程。

So 3 requests to the server within the same Web Application will share the same AppDomain. 因此,对同一Web应用程序中的服务器的3个请求将共享同一AppDomain。

How that affects caching and singletons: 这如何影响缓存和单例:

From the docs on System.Web.Caching.Cache : System.Web.Caching.Cache上的文档中:

One instance of this class is created per application domain, and it remains valid as long as the application domain remains active. 此类的一个实例是在每个应用程序域中创建的,只要该应用程序域保持活动状态,它就一直有效。

When you lock an object (like a singleton) the lock's scope is an AppDomain as well. 当您锁定对象(如单例)时,锁定的范围也为AppDomain。

Yours instance - process and yours 3 requests - executed by threads. 您的实例-进程和您的3个请求-由线程执行。 So singleton object will be shared between all 3 requests. 因此,单例对象将在所有3个请求之间共享。 Your cache also will be shared between requests. 您的缓存也会在请求之间共享。 In your example you will allocate only 1 Mb (it will update 10 times). 在您的示例中,您将仅分配1 Mb(它将更新10次)。 Garbage collector will collect unused space. 垃圾收集器将收集未使用的空间。

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

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