views:

132

answers:

3

Hi folks:

I intend to around existing code snippet (updating a Hashtable) with lock() block to prevent multiple threads (launched by ASP.NET web site) from simultaneously updating a Hashtable.

B\c this is first time I do in this measure, I need your advice on

  1. Any performance overhead caution caused by lock()
  2. Any other issues you ever experienced similar to this scenarios.

I appreciate any advices.

+1  A: 

lock is okay, a better approach would be the ReaderWriterLock(Slim). Matt provides a nice wrapper that allows usage in a using-block.

Marc Wittke
+1 ReaderWriterLock is more performant for such scenarios
ssg
@Marc, @ssg: The `Hashtable` class is thread-safe for multiple readers and a single writer, so a `RWL`/`RWLS` would probably be overkill in this situation. A standard `lock` around any writer code should do the trick and give better performance. (Note that this only applies to the non-generic `Hashtable` class, *not* `Dictionary<K,V>` etc.) http://msdn.microsoft.com/en-us/library/system.collections.hashtable.aspx
LukeH
Not much know what situation would need ReaderWriterLockSlim.I just put lock around the code updating Hashtable; no lock around codes regarding reading it.
Ricky
+1  A: 

Best practices for lock() are to make sure you lock on a private static object (see here on MSDN for why). I would also highly recommend reading Threading Best Practices before heading down this road.

Usually though, performance overhead from lock() is going to be less of a worry than how many threads it's blocking, and how often. You should make sure you understand the profile of your application so that you can minimize the locking behaviour.

I would highly recommend that you consider using the ASP.Net Application object for simple data storage and updating, as it already has a dictionary and specific methods available for this kind of synchronized storage. Application has Lock() and Unlock() methods that are built to handle thread blocking and failure recovery for you already, without the AppDomain related issues that you might run into by rolling your own syncronization code. An example would be:

Application.Lock();
Application["SomeGlobalCounter"] = (int)Application["SomeGlobalCounter"] + 1;
Application.UnLock();
womp
+1  A: 

In addtion to the posters above I would recommend reading about ReaderWriterLockSlim

Greco
No much know what situation would need ReaderWriterLockSlim.I just put lock around the code updating Hashtable; no lock around codes regarding reading it.
Ricky