开发者

problem with concurrent users when data stored in Lists defined as public static

开发者 https://www.devze.com 2023-02-14 16:30 出处:网络
I have a web project wherein I have various functions that either add values to a series of lists that are defined as public static (so as to have them essentially act as global variables) or read fro

I have a web project wherein I have various functions that either add values to a series of lists that are defined as public static (so as to have them essentially act as global variables) or read from them.

The function that adds data to the list reads from a stream, various things happen and then when the user clicks a button the list is read and for each value contained therein an action is performed.

Everything works fine except when concurrent users are accessing the web page....in this instance the data that is stored in the lists is merged with the data that is created as a result of user interaction.

So the question is how can I preserve the ability for a list to be read from/written to f开发者_运维百科rom different functions without encountering concurrency issues? I can't find a way to create/populate the lists within one function and then make it available to others on the page.

Thanks


Store the values in the Session, instead of static lists. As you found out, a static variable is shared between all users of the site.


To have public static in web application in general is bad idea unless you know what you are doing. Web app is multi-threaded. If you really need shared list you should use locking or thread safe containers...


static items should generally be a: minimised, and b: thread-safe. In any threaded scenario you are otherwise at a great risk of problems from concurrency - and ASP.NET is very, very threaded.

Personally, I just wouldn't here - having public access to a static list is doomed to failure. I might have a private list and some static helper methods that lock(someLock) and obtain a specific item etc, but I'd look at it for a long while to decide if it "smells". Note also that static doesn't work well with multi-tenancy.

0

精彩评论

暂无评论...
验证码 换一张
取 消