mikha
asked on
static in C#
My understanding of static class or member is that , we have only one copy.
consider following class with static members, say I have multiple instances of class Foo and I try to call static methods or access static member. doesn't it run into race condition?
or in other words , do we have to worry about race conditions, when we create static class or static members?
var one = new Foo();
var two = new Foo();
var three = new Foo();
public class Foo{
private static string = "foo";
public int GetCount() {
//return count;
}
}
consider following class with static members, say I have multiple instances of class Foo and I try to call static methods or access static member. doesn't it run into race condition?
or in other words , do we have to worry about race conditions, when we create static class or static members?
var one = new Foo();
var two = new Foo();
var three = new Foo();
public class Foo{
private static string = "foo";
public int GetCount() {
//return count;
}
}
do we have to worry about race conditionsIf you're going to multi-thread, then yes. Otherwise, there's only one thread, and there can't be a race condition with only one thread.
ASKER
thanks @käµfm³d and Kyle Abrahams.
what about ASP.NET MVC applications. does each http request have their own thread or how does it work ?
what about ASP.NET MVC applications. does each http request have their own thread or how does it work ?
Yes, ASP.NET is multi-threaded, and each request gets its own thread.
ASKER
thanks @käµfm³d . one last clarification then. I see many helper static classes/methods written by developers in ASP.NET projects, without making it thread safe. isn't this a issue then? or am i not understanding this right? or is it a problem when we are accessing/modifying static variables in those static methods?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
https://www.cis.upenn.edu/~matuszek/cit591-2006/Pages/static-vs-instance.html
To answer your question, yes, race conditions are a worry as any instance updating the static variable should affect the other instances.
Note though that you could only access the static member by the class name, not by the instance name.
Open in new window