how to synchronize a hash table

Hello,

I wrote a test that calls the method EnumerateUsers simultaneously by N number of threads in a test app. (The actual object is exposed thru asp.net web services. UserManager is a singleton object in the webservice).

The problem I'm seeing is that when I'm seeing this.Add throw a dup-key exception because the key already exists in the hashtable.

I added instrumentation that showed synchronization at the "thisLock_" looks fine...threads are entering and exiting fine. However, i see that Add throw the exception, and the count of the hashtable is 1 (in the catch block) .

I must be doing this incorrect. Anyone have a tip? Thanks!

public class UserManager : Hashtable

private static Object thisLock_ = new Object();

public void EnumerateUsers()
{
lock (thisLock_)
{

DataReader dataReader ReadDatabase(sqlForUsers);
this.Clear();
while (dataReader.Read())
{
User user = new User(dataReader);
this.Add(user.Guid, user);
}
}

[1100 byte] By [Steve1999] at [2007-12-25]
# 1

Hello,

There is a book by Microsoft "Improving Performance of Managed Application". Sorry I could not find link to online version whic i saw before but here is a PDF of the same: http://www.microsoft.com/downloads/details.aspx?familyid=8A2E454D-F30E-4E72-B531-75384A0F1C47&displaylang=en

This Includes all the issues regarding Performance and also the effective use of Collections and Threading together.

I hope this will help you.

Best Regards,

RizwanSharp at 2007-9-3 > top of Msdn Tech,Visual C#,Visual C# General...
# 2
Murky. The user.Guid property might not be unique of course. More likely: if UserManager is a singleton and EnumerateUsers() is called by multiple threads, you would expect the DataReader object to return the same set of users. The 2nd thread that calls EnumerateUsers() is going to try to add a user that is already added by the 1st thread. Use the ContainsKey() method to avoid adding one that already exists...
nobugz at 2007-9-3 > top of Msdn Tech,Visual C#,Visual C# General...
# 3

There's a clear inside the lock. The collection is cleared before users are added.

Steve1999 at 2007-9-3 > top of Msdn Tech,Visual C#,Visual C# General...