C. Ross
C. Ross

Reputation: 31848

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?

Upvotes: 4

Views: 3978

Answers (3)

John Saunders
John Saunders

Reputation: 161781

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.

Upvotes: 2

JoshBerke
JoshBerke

Reputation: 67108

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.

Upvotes: 1

Kibbee
Kibbee

Reputation: 66132

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.

Upvotes: 1

Related Questions