We're using a hashtable to store sessions in a web service. I want to test thread safety of adding to this session. I wrote a Console App which generates lots of threads and adds to this session. But I am neither getting an exception nor losing any data. Am I doing anything wrong or isn't this much of operation a threat to hashtable?!
- The key is generated randomly.
The operations done on this hashtable are fairly simple: Add, Remove, ContainsKey, [] (getting an entry) and sometimes updating the value of an entry - no foreach or loop.
private const int Threads = 10000; private const int SleepLimit = 10000; public static void Main(string[] args) { try { Console.WriteLine("Application Started.");
} private static Thread CreateThread() { Thread thread = new Thread(UserFunction); thread.Start(); return thread; } private static void UserFunction() { Thread.Sleep(_random.Next(SleepLimit)); SessionManagement.AddSession("Test"); } public static void AddSession(string session) { ulong hash = NextHashValue(); while (_sessionPool.ContainsKey(hash)) { Console.WriteLine(string.Format("Duplicate Session Key: {0}-PoolSize: {1}", hash, _sessionPool.Count);Thread[] threads = new Thread[Threads]; for (int i = 0; i < threads.Length; i++) threads[i] = CreateThread(); Console.WriteLine("All Threads Started."); foreach (Thread t in threads) t.Join(); Console.WriteLine("All Threads Joined."); } catch (Exception ex) { Console.WriteLine("Exception occurred: " + ex.Message); Console.ReadLine(); }
}hash = NextHashValue(); } _sessionPool.Add(hash, session); if (!_sessionPool.ContainsKey(hash)) Console.WriteLine("Race problem occurred - Session Key: " + hash);