Synchronised Generic List

G

Guest

Hi,

I am considering using a Generic List to hold user defined class entries.
Since this List will be accessed by multiple threads I need it to be
threadsafe. It appears there is no easy way to do this as there is no
synchronised method for the list.

I suppose I could lock the List whenever I access it but I am concerned this
will affect performance as the list will be accessed frequently.

Can anyone suggest how i can accomplish this syncronisation?

Thanks
Macca
 
B

Barry Kelly

Macca said:
I am considering using a Generic List to hold user defined class entries.
Since this List will be accessed by multiple threads I need it to be
threadsafe. It appears there is no easy way to do this as there is no
synchronised method for the list.

I suppose I could lock the List whenever I access it but I am concerned this
will affect performance as the list will be accessed frequently.

A synchronized List<T> would perform in the same way as a list that you
lock yourself, since it would be implemented in this way. I.e.
ArrayList.Synchronized doesn't return a lock-free list - it simply
returns a list which locks the inner list during every call.

If the list won't be modified very often but will be accessed extremely
often (and you've measure performance and know that contention is the
reason for poor performance), you could consider using copy / modify /
atomic replace pattern. I.e. make a copy of the list whenever you're
about to change it, change the copy, and then use
Interlocked.CompareExchange to perform a swap, and repeat the copy /
change operation if the reference has changed in the meantime. If you
don't want to deal with the subtleties of things like memory read and
write barriers etc., that probably won't be the way to go.

-- Barry
 

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

Top