Lock generic SortedList

  • Thread starter Thread starter Oscar Thornell
  • Start date Start date
O

Oscar Thornell

Hi,

Any comments regarding this implementation...

SortedList<String, String> list = new SortedList<String, String>();

lock (((IList)list).SyncRoot)
{
foreach (Object item in list)
{
//Do some stuff...
}
}

Regards
/Oscar
 
Well, unless there are some missing lines that make the list available to
another thread, you don't really need to lock it anyway... of course, by
that reasoning the list is also empty, which I'm sure it isn't ;-p

IIRC, the base foreach of a dictionary is a KeyValuePair<TKey,TValue>; you
might choose to enumerate .Values or .Keys, which will allow direct access
to the strings; otherwise, using the base foreach I would cast "item"
correctly - i.e. as a KeyValuePair<string,string>.

If the list is reasonably short, and you want to minimise lock times, and
the specific scenario permits, then you could perhaps take a spanshot of the
values as an array first (within the lock), and then (outside the lock)
enumerate the items. This assumes you aren't reassigning / adding /
removing, which you can't do inside a foreach anyway (but you can do inside
the same lock, but it isn't shown).

Marc
 
seems OK.. except it may keep the list locked for some extra time depending
the operation you do there..

Nirosh.
 
Ok! Great! Thanks a bunch!
Just wanted a second opinion since it´s the first time I needed to deal with
thread saftey and generic collections..

/Oscar
 
If this is all you're doing, you don't need the lock (but you already knew
that).

That said, if you need to lock the collection this is a valid way to do it.
You can also look into Reader-Writer Locks depending on your use case.

You could also wrap your sorted list in the generic ReadOnlyCollection class
(this also implements IList), that way you could avoide the locks
altogether.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top