Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to synchronize the access to a List<T> used in ASP.NET?

I have some problems on a site with the concurrent access to a list. This list keeps a cart of items, and multiple deletes are crashing the site. Which is the best method to sync them? Is a lock enough? The lock option seems to be ugly because the code is spread all over the place and is pretty messy.

Update: This is a list implemented like this: public class MyList : List< SomeCustomType> { }

This is a legacy site so not so many modifications are allowed to it. How should I refactor this in order to safely lock when iterating over it ?

any idea!

like image 755
Adrian Magdas Avatar asked Oct 09 '08 09:10

Adrian Magdas


3 Answers

So is this in-memory list shared between requests? That sounds like a potential cause of problems even when you've got locking. Mutable shared collections should generally be avoided, IME.

Note that if you do decide to synchronize, you'll need to do things like locking the list for the whole course of iterating over it and other compound operations. Just locking on each specific access isn't good enough.

like image 67
Jon Skeet Avatar answered Oct 04 '22 01:10

Jon Skeet


Using lock is the correct way to synchronize access to generic collections. access to the collection is spread all over the place, you can create a wrapper class to wrap access to the collection so the interaction surface is reduced. You can then introduce synchronization inside the wrapping object.

like image 27
Samuel Kim Avatar answered Oct 04 '22 03:10

Samuel Kim


Yes, you have to lock- using List.SyncRoot like this:

lock (myList.SyncRoot) 
{
    // Access the collection.
}
like image 30
martin Avatar answered Oct 04 '22 02:10

martin