views:

28

answers:

1

I have a custom CMS in which I use an static XElement as the site map. When updates occur to the map, I am synchronizing the writer threads, but am doing nothing with the readers, just allowing them to grab the XElement when they need it.

In testing, I thought that if I was enumerating the XElement from a reader thread, while I updated it on another writing thread, I would get an exception. That was not the case. Just wondering if anyone can explain to me if they see any major issues with this approach. It doesn't seem like it should be safe, but all my testing so far has indicated that it is.

A: 

Use a System.Threading.ReaderWriterLock to control access to the XElement. That way you synchronise all readers and any writers without blocking concurrent read activity.

AnthonyWJones
Should the locking be done on the XElement itself or a shared static object?
You won't be using the lock function in this case (which internally uses the Monitor class I think). You would create a static instance of ReaderWriterLock which would be your "lock" object you then call AquireReaderLock or AcquireWriterLock methods as needed. Note you are responsible for ensuring you call the appropriate Release method even under error conditions. Hence you need to make sure you enter a Try block after aquiring a lock and include the appropriate Release call in the Finally block.
AnthonyWJones