Mark,
You should clarify what you mean by "row level". The statement itself
says that you want to lock operations on a specific row, however your code
says something different. It seems like what you want to do is isolate
operations on a thread that deal with an element in the hash table.
Your code is only off by a little bit. Instead of locking on
ht["row1"], you should lock on ht. The reason for this is that ht["row1"]
will return an object, but it doesn't synchronize access to the hashtable
itself. Since you are trying to change what a key is associated with, you
have to work on this level.
Now, because you have a synchronized version of the hash table, you
don't have to use the lock statement at all. It's built in for you.
If you didn't have the synchronized hash table, then you would have to
do:
static void Main(string[] args)
{
lock (ht)
{
ht["row1"] = "hello world";
}
lock (ht)
{
Console.WriteLine(ht["row1"]);
}
lock (ht)
{
ht["row1"] = "hi there";
}
lock (ht)
{
Console.WriteLine(ht["row1"]);
}
Console.ReadLine();
}
Now, all of those lock blocks could be combined in various ways. That
depends on how you want your operations to be broken up, and if you want
other threads to have access to any blocks of code locked with ht in between
operations.
Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
-
mv*@spam.guard.caspershouse.com
"Mark S." <ma***@yahoo.comwrote in message
news:%2****************@TK2MSFTNGP05.phx.gbl...
Much to my surprised the code below compiled and ran. I just don't know
enough about threading to know for sure if this is too good to be true.
I'm attempting to isolate the Hashtable lock to "row level", the whys
aren't important at this time. Does this code actually do what I want?
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace ConsoleForTesting
{
class testHashTableElementLock
{
public static Hashtable ht = Hashtable.Synchronized(new
Hashtable());
static void Main(string[] args)
{
ht["row1"] = "hello world";
Console.WriteLine(ht["row1"]);
lock (ht["row1"])
{
ht["row1"] = "hi there";
}
Console.WriteLine(ht["row1"]);
Console.ReadLine();
}
}
}