What are static C# class variables for in ASP.NET? - c#

I know what static class variables do in a C++ class, what I'm not very clear about is the life-cycle of static class variables in a C# class used for an ASP.NET web app. Here's a code example:
namespace MyWebApp
{
public static class MyFunctions
{
private static string _cachedID;
public static string getID(string strValue)
{
if(_cachedID == null)
_cachedID = strValue;
return _cachedID;
}
}
}
Can someone explain it in plain English for me?

I've read somewhere.
A static variable/field comes into existence before execution of the static constructor for its containing type, and ceases to exist when the associated application domain ceases to exists.

Since you are asking this question in the context of a multithreaded ASP.NET application, you should be extremely careful. Checkout the following scenario:
2 users Bob and Alice call the getID method at exactly the same time passing different arguments. Bob passes Foo and Alice passes Bar. Since this is the first call, the _cachedID variable is not yet initialized so both enter the if condition, Bob with a slight delay. So Alice sets the _cachedID static variable to Bar and a microsecond after, Bob sets it to Foo. Now the code continues and the function returns Foo for both users. Bob of course is happy because that's what he wanted, but Alice wanted Bar.
For example if you wanted to perform a one time initialization in a multithreaded environment you might consider using the thread safe version of the Singleton Pattern.
The moral of this is that you should be extremely careful when dealing with shared/static data in an ASP.NET application. If you need to use it you need to properly synchronize the access to it or very bad things could happen. And they usually happen in production when your application is concurrently accessed by multiple users. On your local PC everything will work fine.
And back to your original question about the lifetime of a static fields: it is tied to the lifetime of the application domain.

Classes which you can't and dont have to make an object of but you can only acces it from a static context.
you would use your example like this:
MyFunctions.getID("bla");
http://msdn.microsoft.com/en-us/library/79b3xss3(v=vs.80).aspx

Related

Will InstanceContextMode.PerCall in WCF instantiate all static variables/methods?

In my WCF code, user's id and name are stored in static variables. It is retrieved from HttpContext.Current.User.Identity.Name and a database hit. Also there are other static variables to store connection string, log file related stuff etc.
Recently i found myself in a race condition where a second call from my client set the user name when the first call was still processing. This resulted in first call reading user data updated by the second call.
To avoid this, I read about InstanceContextMode.PerCall and how it makes static variables behave like non-static for every call.
My questions are
1) If i use InstanceContextMode.PerCall, does that mean it will instantiate all static variables and methods? I am planning to use this only to get new user data for every call. However, I assume this will also make a new instance for connection string static variable, log file and other static variables. Is this correct? Will it affect performance (reading again from web.config etc)?
2) Is there a way to use InstanceContextMode.PerCall but to create instance only for user data related static variables and leave the connection string related static variables?
3) Is a dispose method ( implementing IDispose) mandatory to dispose off the static variables once the call is done?
First of all not sure why you have all those data in a static variable? that looks like a bad design. When you say InstanceContextMode.PerCall; to my understanding every call have a separate copy of the data and it's unique per call.
If you want your data to be not modified then try declaring them as static readonly instead. Lastly, you should opt for a better design rather.

Sync Lock issue in Parallel.Foreach

I have worked with c# code for past 4 years, but recently I went through a scenario which I never pass through. I got a damn project to troubleshoot the "Index out of range error". The code looks crazy and all the unnecessary things were there but it's been in production for past 3 years I just need to fix this issue. Coming to the problem.
class FilterCondition
{
.....
public string DataSetName {get; set;}
public bool IsFilterMatch()
{
//somecode here
Dataset dsDataSet = FilterDataSources.GetDataSource(DataSetName); // Static class and Static collection
var filter = "columnname filtername"
//some code here
ds.defaultview.filter= filter;
var isvalid = ds.defaultView.rowcount > 0? true : false;
return isValid;
}
}
// from a out side function they put this in a parallel loop
Parallel.ForEach()
{
// at some point its calling
item.IsFiltermatch();
}
When I debug, dsDataSet I saw that dsDataSet is modified my multiple threads. That's why race condition happens and it failed to apply the filter and fails with index out of Range.
My question here is, my method is Non-static and thread safe, then how this race condition happening since dsDataset is a local variable inside my member function. Strange, I suspect something to do with Parallel.Foreach.
And when I put a normal lock over there issue got resolved, for that also I have no answer. Why should I put lock on a non-static member function?
Can anyone give me an answer for this. I am new to the group. if I am missing anything in the question please let me know. I can't copy the whole code since client restrictions there. Thanks for reading.
Because it's not thread safe.
You're accessing a static collection from multiple threads.
You have a misconception about local variables. Although the variable is local, it's pointing at an object which is not.
What you should do is add a lock around the places where you read and write to the static collection.
Problem: the problem lies within this call
FilterDataSources.GetDataSource(DataSetName);
Inside this method you are writing to a resource that is shared.
Solution:
You need to know which field is being written here and need to implement locking on it.
Note: If you could post your code for the above method we would be in a better position to help you.
I believe this is because of specific (not-stateless, not thread safe, etc) implementation of FilterDataSources.GetDataSource(DataSetName), even by a method call it seems this is a static method. This method can do different things even return cached DataSet instance, intercept calls to a data set items, return a DataSet wrapper so you are working with a wrapper not a data set, so a lot of stuff can be there. If you want to fine let's say "exact line of code" which causes this please show us implementation of GetDataSource() method and all underlying static context of FilterDataSource class (static fields, constructor, other static methods which are being called by GetDataSource() if such exists...)

does aspx provide special treatment for c# static variables

in a .net web app is there something special about .aspx pages and the c# code behind pages that changes the behaviour of static variables.
i have a large number of application pages that were developed elsewhere and there is a common pattern running thru them where what i think should be an instance variable is declared as a static variable.
a more detailed statement of the question would be: if i have two web sessions a and b running on the same iis server in the same application pool, if a accesses the page in question and sets static variable x to value1 and then b accesses the same page and sets static variable x to value 2, my understanding is that value1 has been replaced by value 2. my dilemma is that this pattern is used repeatedly in the code, at a high level the code appears to work. the conclusion is that it is either luck (timing as in session a has abandoned the need for the variable before session b hits it) or there is something else going on.
i am open to suggestions whether this is a c# nuance or a developer bug.
Static properties/fields are fine in web applications as long as they are used for shared data which can acceptably disappear at any time, such as when an app pool recycles.
That said, their values are indeed shared inside an ASP.Net application unless they have a segregated backing mechanism, like Session.
Example
public static int UserId = 10; // BAD! everyone gets/sets this field's value
// BAD! everyone gets/sets this property's implicit backing value
public static int UserId {
get;
set;
}
// This case is fine; just a shortcut to avoid instantiating an object.
// The backing value is segregated by other means, in this case, Session.
public static int UserId{
get{
return (int)HttpContext.Current.Session["UserId"];
}
}
// While I would question doing work inside a property getter, the fact that
// it is static won't cause an issue; every call retrieves data from a
// database, not from a single memory location.
public static int UserId{
get{
// return some value from database
}
}
You may not see an issue until traffic is significant. Suppose a page retrieves a value, puts it in a static variable, uses it once, then completes execution. If the page executes quickly, there is only a very small (but dangerous!) window of overlap that you may not see unless the timing is right and/or traffic is high enough.
This can lead to hard-to-diagnose bugs, because they are dependent on timing and you probably will not see them when testing by yourself on your local machine.

How do static events compare to non-static events in C#?

I just realized static events exist - and I'm curious how people use them. I wonder how the relative comparison holds up to static vs. instance methods. For instance, a static method is basically a global function. But I've always associated events with instances of objects and I'm having trouble thinking of them at the global level.
Here some code to refer to if it helps an explanation:
void Main()
{
var c1 = new C1();
c1.E1 += () => Console.WriteLine ("E1");
C1.E2 += () => Console.WriteLine ("E2");
c1.F1();
}
// <<delegate>>+D()
public delegate void D();
// +<<event>>E1
// +<<class>><<event>>E2
// +F()
// <<does>>
// <<fire>>E1
// <<fire>>E2
public class C1
{
public void F1()
{
OnE1();
OnE2();
}
public event D E1;
private void OnE1()
{
if(E1 != null)
{
E1();
}
}
static public event D E2;
static private void OnE2()
{
if(E2 != null)
{
E2();
}
}
}
Be wary of static events. Remember that, when an object subscribes to an event, a reference to that object is held by the publisher of the event. That means that you have to be very careful about explicitly unsubscribing from static events as they will keep the subscriber alive forever, i.e., you may end up with the managed equivalent of a memory leak.
Much of OOP can be thought of in terms of message passing.
A method call is a message from the caller to the callee (carrying the parameters) and a message back with the return value.
An event is a message from the source to the subscriber. There are thus potentially two instances involved, the one sending the message and the one receiving it.
With a static event, there is no sending instance (just a type, which may or may not be a class). There still can be a recipient instance encoded as the target of the delegate.
In case you're not familiar with static methods
You're probably already familiar with static methods. In case you're not, An easy-to-understand difference is that you don't need to create an instance of an object toi use a static method, but you DO need to create an instance of an object to call a non-static method.
A good example is the System.IO.Directory and System.IO.DirectoryInfo classes.
The Directory class offers static methods, while the DirectoryInfo class does not.
There are two articles describing them here for you to see the difference for yourself.
http://visualcsharptutorials.com/2011/01/system-io-directory-class/
http://visualcsharptutorials.com/2011/01/system-io-directoryinfo-class/
Now on to static events...
However, static events are seldom seen in the wild. There are very few cases that I can think opf where I'd actually want to use one, but there is a CodeProject article that does show one potential use.
http://www.codeproject.com/KB/cs/staticevent.aspx
The key thought here is taken from the explanation (bold added by me to point out the relevant text):
We saw this property as a separate object and we made sure that there
is only one instance of it at a time. And all instances of
transactions knew where to find it when needed. There is a fine
difference though. The transactions will not need to know about the
changes happening on the exchange rate, rather they will use the last
changed value at the time that they use it by requesting the current
value. This is not enough when, for example, we want to implement an
application where the user interface reacts immediately on changes in
the UI characteristics like font, as if it has to happen at
real-time. It would be very easy if we could have a static property
in the Font class called currentFont and a static method to change
that value and a static event to all instances to let them know when
they need to update their appearance.
As .NET developers we're trained to work with a disconnected model. Think of ADO.NET compared to classic ADO. IN a VB6 app, you could use data controls that would allow the following functionality: If you were running the app on your PC, the data in your grid would update when someone on another PC edited the data.
This isn't something that .NET developers are used to. We're very used to the disconnected model. Static events enable a more "connected" experience. (even if that experience is something we're not used to any more.)
for some insight check this link http://www.codeproject.com/KB/cs/staticevent.aspx
static event can be used
when no instance exists
to do some multicast event for all existing instances...
when you have a static class which can fire events...
BUT one should use them with cuation... see discussion http://groups.google.com/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/2ac862f346b24a15/8420fbd9294ab12a%238420fbd9294ab12a?sa=X&oi=groupsr&start=1&num=2
more info
http://msdn.microsoft.com/en-us/library/8627sbea.aspx
http://dylanbeattie.blogspot.com/2008/05/firing-static-events-from-instance.html
http://www.nivisec.com/2008/09/static-events-dont-release.html
Static members are not "global," they are simply members of the class, not of class instances. This is as true for events as it is for methods, properties, fields, etc.
I can't give an example for using a static event, because I generally don't find static members to be useful in most cases. (They tend to hint at anti-patterns, like Singleton.)

Static methods in a class - okay in this situation?

Hey all - I have an app where I'm authenticating the user. They pass username and password. I pass the username and password to a class that has a static method. For example it'm calling a method with the signature below:
public class Security
{
public static bool Security.Member_Authenticate (string username, string password)
{ //do stuff}
}
If I have 1000 people hitting this at once, will I have any problems with the returns of the method bleeding into others? I mean, since the methods are static, will there be issues with the a person getting authenticated when in fact they shouldn't be but the person before them was successfully authenticated ASP.Net returns a mismatched result due to the method being static? I've read of issues with static properties vs viewstate but am a bit confused on static methods. If this is a bad way of doing this,what's the prefered way?
This will not happen. When a method is Static (or Shared in VB.NET), then you're safe as long as the method doesn't rely on anything other than the inputs to figure something out. As long as you're not modifying any public variables or objects from anywhere else, you're fine.
A static method is just fine as long as it is not using any of persistent data between successive calls. I am guessing that your method simply runs a query on the database and returns true/false based on that.
In this scenario, I think the static method should work without a problem, regardless of how many calls you make to it.
ASP.net does use all sorts of under-the-hood thread pooling, which can make static methods and fields dicey.
However, you can avoid most threading issues with a static method by using only locally-scoped variables in that method. That way, each thread (user) will have their own in-memory copy of all the variables being used.
If you use higher-scoped variables, make sure to make all access to them thread-conscious.
Throwing exceptions is not a good practice as it makes the .net runtime to create extra infrastructure for catching them. To verify this create a class and and populate it with some random values using a loop. Make the loop iterate for a large counter like 10,000. Record the time it takes to create the list. Now enclose the instance creation in a try..catch block and record the time. Now, you can see the exceptionally large difference.
e.g
for(int i=0; i<10000; i++){
Employee emp = new Employee();
emp.Name = "Random Name" + i.ToString();
}
Versus
for(int i=0; i<10000; i++){
try{
Employee emp = new Employee();
emp.Name = "Random Name" + i.ToString();
}catch{}
}
Although there is no fixed solution whether to throw exception or not, it is a best practice to create alternate flows in your program and handle every condition with proper return values. Exceptions should be thrown only when the situation can be justified as exceptional.
While I can see the value of the static method in regards to the perceived performance gains, I believe the real issue here is whether the gains (and risks) are worth the maintenance kludge and security weakness you are potentially creating. I believe that most people would warn you away from providing a public method that accepts an user credentials and returns success or failure. It potentially provides an easy a method for hacking.
So, my point is philosophical. Otherwise, I agree with others who have pointed out that restricting the code to use local variables should ensure that you do not have any problems with side effects due to concurrent access of the method, even on different threads, i.e., if you invoke the method on a ThreadPool thread.
Maybe it's better to use public static void Authenticate(string, string) which throws an exception if something goes wrong (return false in original method) ?
This is a good .NET style. Boolean function return-type is the C style and is obsolete.
Why don't you have the user class with username and password and a method that is called authenticate?

Categories