ASP.NET Global/Static storage? - asp.net

I have a thread-safe object which is part of an API previously used in windows service/client scenarios. This thread-safe object is essentially a singleton and stored in a static variable so that all callers can access the same state.
This API has recently started being used in an ASP.NET application, and I suspect that some funky behavior we're seeing may be due to unexpected AppDomain/lifecycle behavior. So I was wondering if I could get some verification:
Is a static variable reliably available for all requests, or does ASP.NET do any trickery with having multiple AppDomains for multiple requests?
I understand this would be the case for a web garden ... but our IIS is configured to use only 1 process, and is configured to only recycle once a day

Static variable should be the same for all requests in 1 worker process. I would suggest you to add logs to your asp.net application, especially in application_start/stop and in static constructor of a singleton to see what's happening.
Hope this helps.

Related

.net webservice and simultaneous access

I am trying to understand basic flow in a .net webservice.
Is the service instantiated again and again for different client connections? If I have a static class/members are they shared across? How is api concurrency maintained?
I guess my question is the application context/memory/address space shared across different requests (from say different users) or somehow the requests are sandboxed?
What you need to understand is instancecontextmode
Static memebers are shared within a process.
If instancecontext mode is not single then specify concurrency attribute.
Please refer this before proceeding.

How many instances of a web application are running in one worker process?

I have a single ASP.NET MVC 4 web application (MvcApplication which extends System.Web.HttpApplication) hosted on IIS 8. My application is running on a separate application pool in integrated pipeline mode. Maximum worker process count for this application pool is set to 1.
I understand, that application instances might get pooled and there might be multiple parallel threads, which will call Begin_Request/End_Request for the same instance of my application (AppDomain). Also I understand that if I set "Maximum worker process count" to more than 1 then there will definitely more than one instance of the application (AppDomain).
What I don't understand is how many calls to Application_Start will be issued and how many instances of my static variables (stored in MvcApplication and also there are some singletons, like NHibernate session factory etc.) will exist at a given moment.
Currently I have some problems with cleaning up .NET MemoryCache. Some users of my website are receiving old values from the cache, thus leading me to think that there might exist more than one instance of my global MemoryCache, even when I set "Maximum worker process count" to 1.
What is the maximal number of instances of my application static variables and singletons which will be run in parallel in a single worker process?
Is there any utility or script which would help me to enumerate all AppDomains on IIS?
I'm not sure if this applies to you, but HttpModule Initialize methods are called more than once because even though there is only one Application instance. One HttpApplication can spawn multiple HttpModule instances, so make sure those initializations are thread safe.
Application_Start and _End will fire only once per site start and stop with your current settings, so that will not be the issue. If you are using the HttpContext.Cache object, you might have the issue mentioned in this answer:
HashTable in HttpContext.Current.Cache
If you want, you can try using WinDbg and get a dump of what is going on in your process but that is a really heavy-handed tactic that probably won't shed as much light as just looking through the code. Not until you look at it a little harder, and are still stumped IMO.

Multithreading in application servers

"Even though you do not use Threads in an application explicitly, its bound to be thread unsafe if you are talking about web server applications".
I just want to understand this clearly. Assume i have a restful service (ASP.net ; will talk about asp.net web application in picture). If there are two simultaneous requests to the same web method A, both of these are going to be served by different thread of the IIS wp. Now, what are these 2 threads working on? ie. Are these two threads accessing A on the same instance of the service class?
How can we validate the fact that these 2 requests are/ are not working on the same instance of the service class so that there is infact a thread unsafety here because of instance variables being accessed in the web method
> Now, what are these 2 threads working on?
Short answer threads of IIS. You need clarify architecture of IIS - think about this as stand alone program. It can plug (dynamically load) lot of DLLs. One of it is ASP.Net interceptor (it accept extensions looked like *.aspx, *.ashx, ...) In other turn this DLL loads your DLLs produced from your code. So to handle request from client side IIS (in general case) starts thread (let me skip discussion of pooling).
> How can we validate the fact that these 2 requests are/ are not working on the same instance of the service class
In scenario above you don't need to validate, since ASP.Net will create as many instance as you need. The problem appears when you use asynchronous request feature (see http://msdn.microsoft.com/en-us/magazine/cc163725.aspx)
<%# Page Async="true" ... %>
Or start some threads manually.
In both cases you could apply really powerful set of synchronization primitives to detect if some resource is shared between 2 or more threads. Using atomic increments (Interlocked.Increment/Decrement) or Monitor with TryEnter methods (for details see http://msdn.microsoft.com/en-us/magazine/cc188793.aspx)

ASP.NET A static object to hold connection with a DB. Is it a good idea?

I'm wondering if it is a good approach in the ASP.NET project if I set a field which "holds" a connection to a DB as a static field (Entity Framework)
public class DBConnector
{
public static AdServiceDB db;
....
}
That means it'll be only one object for entire application to communicate with a DB. I'm also wondering about if that object will be refreshing data changes from DB tables, or maybe it shouldn't be static and I shoud create a connection dyniamically. What do You think ?
With connection pooling in .NET, generally creating a new connection for each request is acceptable. I'd evaluate the performance of creating a new one each time, and if it isn't a bottleneck, then avoid using the static approach. I have tried it before, and while I haven't run into any issues, it doesn't seem to help much.
A singleton connection to a database that is used across multiple web page requests from multiple users presents a large risk of cross-contamination of personal information across users. It doesn't matter what the performance impact is, this is a huge security risk.
If you don't have users or personal information, perhaps this doesn't apply to your project right now, but always keep it in mind. Databases and the information they contain tend to evolve in the direction of more specifics and more details over time.
This is why you should not use a singleton design pattern with your database connection
Hope it helps
Is using a singleton for the connection a good idea in ASP.NET website
Bad idea. Besides the potential mistakes you could make by not closing connections properly and so forth, accessing a static object makes it very difficult to unit test your code. I'd suggest using a class that implements an interface, and then use dependency injection to get an instance of that class wherever you need it. If you determine that you want it to be a singleton, that can be determined in your DI bindings, not as a foundational point of your architecture.
I would say no.
A database connection should be created when needed to run a query and cleaned up after that query is done and the results are fetched.
If you use a single static instance to control all access to the DB, you may lose out on the automatic Connection Pooling that .NET provides (which could impact performance).
I think the recommendation is to "refresh often."
Since none of the answers have been marked as an answer and I don't believe any have really addressed question or issue thereof...
In ASP.NET, you have Global or HttpApplication. The way this works is that IIS will cache instances of your "application" (that is an instance of your Global class). Normally (default settings in IIS) you could have up to 10 instances of Global and IIS will pick any one of these instances in order to satisfy a request.
Further, keep in mind that, there could be multiple requests at any given moment in time. Which means multiple instances of your Global class will be used. These instances could be ones that were previously instantiated and cached or new instances (depending on the load your IIS server is seeing).
IIS also has a notion of App Pools and worker processes. A Worker process will host your application and all the instances of your Global classes (as discussed earlier). So this translates to an App Domain (in .NET terms).
Just to re-cap before moving on…
Multiple instances of your Global class will exist in the Worker process for your application (in IIS). Each one waiting to be called upon by IIS to satisfy a request. IIS will pick any one of these instances. They are effectively threads that have been cached by IIS and each thread has an instance of your Global class. When a request comes in, one of these threads is called upon to handle the request-response cycle. If multiple requests arrive simultaneously, then multiple threads (each contains an instance of your Global class) will be called upon to satisfy each of those requests.
Moving on…
Since there will be only one instance of a static class per App Domain you'll effectively have one instances of your class shared across all (up to 10) instances of Global. This is a bad idea because when multiple simultaneous requests hit your server they'll either be blocked (if your class’s methods use locks) or threads will be stepping on each other’s toes. In other words, this approach is not inherently thread-safe and if you make it thread safe using thread synchronization primitives then you’re unnecessarily blocking threads, negatively impacting performance and scalability of your web application, with no gain whatsoever.
The real solution (and I use this in all my ASP.NET apps) is to have an instance of your BLL or DAL (as the case may be) per instance of Global. This will ensure the following:
1. Multiple threads are not an issue since IIS guarantees one request-response per instance of Global) at any given moment in time. So you’re code is inherently threads-safe.
2. You only have up to 10 instances of your BLL/DAL up and running at any given moment in time ensuring that you're not constantly creating and disposing instances of (typically) large objects to satisfy each request, which on busy sites is huge
3. You get really good performance well due to #2 above.
You do have to ensure that your BLL/DAL is truly stateless or that you reset any state at the start of each Request-Response cycle. You can use the BeginRequest event in Global to do that is you need to.
If you go down this route, be sure to read my blog post on this
Instantiating Business Layers – ASP.NET

Static fields in an ASP.NET Webservice

Is a static variable in a webservice shared between all running invocations of the webservice on a server?
In my case I want a server-wide sync-lock, and I beleive I can accomplish that with a single
private static Object syncHandle = new Object();
Is that correct?
Yes, they are all shared per AppDomain which is why, in general, they should not be used!
They should not be used, in general, because they are so unlikely to be used properly. Also because there are safer alternatives, like HttpContext.Cache, or even Session state.
Still, if you encapsulate all access to these static members, and if you handle locking correctly, then you'll have a safe implementation that may then turn out to be a bottleneck, with all threads contending for the shared resource. It's really better to do without.
Also, you seem to mean ASMX web services, but you should specify ASMX or WCF.
I believe they are shared as long as they are running in the same process. So two people requesting from the same server would have the same instance of the object. However, you can run different applications in a computer different process on IIS, in which case I'm pretty sure that instances to objects wouldn't be shared.
They are all shared unless you have a Web Garden. A web garden is multiple host process handling a single application. In this case each host will have its own static data.

Resources