Doubt about static methods and classes

Asked

Viewed 419 times

3

I have a question about methods and static classes, given the code below:

    static List<MaterialRCM> mr = new List<MaterialRCM>();

    [Authorize]
    public void AddMaterial(int Qtd, int Id)
    {
        mr.Add(new MaterialRCM(Id, Qtd));
    }

Now, how are static classes and methods not types by reference, if two users use the same functionality runs the risk of having data from both users in the list? To be clearer, this method is called via Ajax, each time the user adds a material this method is called and adds the Material Id and quantity in the list, and if two users are requesting materials?

  • Well, how do you identify in this method which user?

  • Well... there is no identification, but I could put the user ID too, then there would be no problem because I would have the ID of the user who requested the right material? But then, the list would contain the objects of the two users?

  • @I think the question is: static classes and methods are global for the entire application, or only exist by request in the MVC?

  • 1

    @bfavaretto are global for the entire application. The ideal for concurrent access is to put a .lock() on top of the object to be accessed.

  • Yes users shared the same information, and beware this is bad practice!

  • @user3670112 is easy for you to notice such behavior, have two browsers installed on your computer, open the first add items in that list. Then open the other one, you will notice that it will reflect to the other browser, so be careful with this not effective method

Show 1 more comment

1 answer

1


Yes, not only if two users but any request made to the server will access exactly the same value.

In general it is not recommended to use static variables with ASP.Net, not only because it has a single value for all requests but also because it can cause competition problems, since the value could be accessed and modified by more than one thread at the same time, if you need to keep values on the server I would say to use some other way, like Session for example.

  • +1 Perfect....

Browser other questions tagged

You are not signed in. Login or sign up in order to post.