简体   繁体   中英

What is the scope of a static variable in ASP.NET / WCF / IIS?

There are two questions on here which both have highly-upvoted, but seemingly contradictory answers.

What is the actual scope of a static variable?

In my case let's say I have a WCF service running under IIS. Several servers with a load balancer in front. One Site on each server, one App Pool as well. Let's say there's a static variable stored in the class which implements the service.

Will the variable persist across the worker process only? The app pool? The server? I tried to research it but found two competing answers on here.

Under this post: IIS app pools, worker processes, app domains

The reply says "Each worker process is a different program that's run your site, have their alone [own?] static variables"

Yet under this post: Lifetime of ASP.NET Static Variable

The reply says "The static variables are per pool"

Maybe I just don't understand the posts, but they seem contradictory?

It appears I have several worker processes running when I checked. Hence my question.

Any help would be appreciated. I am trying to refactor some stuff away from using static variables since it seems risky and exposes concurrency problems but I am very uncomfortable proposing changes without understanding the current behaviour. Thanks!

Static variables persist for the life of the application domain. So there are 2 things that will reset your static variables is an application domain restart or the use of a new class

Each application pool can have multiple worker processes,

Each worker process will run different application instances.

Each instance of an application has a separate AppDomain - one per application instance.

Static variables are lost when IIS restarts your asp.net application when any of the below happens

  1. The pool decide that need to make a recompile.
  2. You open the app_offline.htm file
  3. manual restart of the app pool
  4. The pool has reached some limits that is defined on the server and restart.
  5. Restart iis

Static variables are not thread safe, and you need to use the lock keyword if you access them from different threads.

Since an app restart will reset your statics variables, and you want to persist data across your application life time, you should store the data persistently in a DB or a file. You can store information per-user in Session State with a database session state mode.

ASP.NET Application State/Variables will not help as they are stored in memory, hence they are not persistent, hence they are lost on app domain restart too.

当我们在Web中定义静态字段时,它将仅与应用程序域限制共享。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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