Link to home
Start Free TrialLog in
Avatar of mikha
mikhaFlag for United States of America

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;
    }
}
Avatar of Kyle Abrahams, PMP
Kyle Abrahams, PMP
Flag of United States of America image

some helpful understanding:
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.

            Foo foo = new Foo();
            Foo foo2 = new Foo();

            Foo.x = "test";
            MessageBox.Show(Foo.x);

    public class Foo
    {
        public static string x = "foo";

    }

Open in new window

do we have to worry about race conditions
If 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.
Avatar of mikha

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 ?
Yes, ASP.NET is multi-threaded, and each request gets its own thread.
Avatar of mikha

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
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial