I have a question regarding static members and functions of non static classes.
I have a static member in my class that I use for authentication. Basically I call a static function from my web application and then inside I call a static function that assigns a value to that static member. Now my question is, will each call to a static function from my web application create a new reference to the object and assign a new value to the static member.
So basically I have this:
public class ClassA
{
private static int UserId;
private static AssignIdToUser(string token)
{
UserId = <int value depending on result of db query>;
}
public SendMessage(string token, string message, string toaddress)
{
AssignIdToUser(token);
Message msg = new Message(); //This is just a sample of a class that is similar to the one I use
msg.Message = message;
msg.UserId = UserId;
msg.ToAddress = toaddress;
//add class to db and save
}
}
Then in my web application I can do:
ClassA.SendMessage("userstoken", "This is a message", "0123456789");
Now if two users log on at the same time and the function gets called at the same time will the member UserId have the correct value for each user?
Basically is a instance of the object created for each request or is the same object used?
An instance of the static member will exist for each
AppDomain, unless you specify[ThreadStatic]in which case it will be per thread, but always per type (note, generics play on this point heavily!)Static members are not a good choice for web apps because IIS recycles AppDomains regularly. You’d lose the static each time it recycled.
User actions are usually stored in
Sessionstate, I’d start here. Assuming ASP.NET:Session State on MSDN
Application State on MSDN