Supposed there is something like Hashtable created by Hashtable.Synchronized() which is accessed by multiple thread. and the key value pair is Guid and Object in Hashtable .
One of thread need to polling this Hashtable until a specific Guid key had been added into this list by another thread.
Below is my code .
public Hashtable syncHt = new Hashtable();
public void Init()
{
Hashtable ht = new Hashtable();
syncHt = Hashtable.Synchronized(ht);
}
In the application initialization i will call the init();
And In one of thread I will call isExist to find the specific Guid which is added by some other thread .
public bool isExist(Guid sId)
{
while (true)
{
if (syncHt.ContainsKey(sId))
{
return true;
}
}
}
I was wondering whether this loop could be ended. How can I know the Hashtable changed during the polling ?Thanks
Reading and more important assigning to a reference is always atomic in .NET.
To do atomic operation, use the
System.Threading.Interlockedclass. See MSDNIt will end when another (only 1 writer allowed) thread inserts the wanted value, yes.
On MSDN: Hashtable is thread safe for use by multiple reader threads and a single writing thread.
But your solution is very inefficient. The busy-loop can consume a lot of CPU time for nothing. Storing (boxed) Guids in an old style collection isn’t perfect either.