public static class PublicValue
{
    private static Hashtable _htSystem = new Hashtable();
    private static object _Root = new object();    public static object Get(string key)
    {
        if (string.IsNullOrEmpty(key))
            return null;
        object result = null;
        lock (_Root)
        {
            if (_htSystem != null)
                result = _htSystem[key];
        }
        return result;
    }    public static void Set(string key, object value)
    {
        if (string.IsNullOrEmpty(key) || value == null)
            return;
        lock (_Root)
        {
            _htSystem[key] = value;
        }
    }
}

解决方案 »

  1.   

    public static class PublicValue
    {
        private static Hashtable _htSystem = new Hashtable();
        private static object _Root = new object();    public static object Get(string key)
        {
            if (string.IsNullOrEmpty(key))
                return null;
            object result = null;
            lock (_Root)
            {
                if (_htSystem != null)
                    result = _htSystem[key];
            }
            return result;
        }    public static void Set(string key, object value)
        {
            if (string.IsNullOrEmpty(key) || value == null)
                return;
            lock (_Root)
            {
                _htSystem[key] = value;
            }
        }
    }
    OK
      

  2.   

    对操作htSystem 这个hash的函数加锁后,是不是也可以达到一个线程访问后,另一个线程无法访问的目的?为什么我给函数加锁后,还出现多线程同时操作htSystem的情况出现呢?
      

  3.   

    lock(obj)
    {
      //
    }obj即为信号量,当被锁住时,其它线程不能进入,只有它完成任务后释放后其它的线程才能进入,这就是说的线程安全。
      

  4.   

    我是这样做的,做一个线程池,然后线程池负责线程的创建,线程池创建线程后,线程内部有这个函数,一个是主函数,一个是私有的函数,在这个私有的函数中,我要对htSystem进行操作(htSystem是属于一个全局类),我现在想对这个私有函数进行加锁,我在主函数中调用这个私有函数时加了
    lock(this)
    {
      //调用私有函数
    }但是我发现这个私有函数还是被多个线程同时访问?为什么呢?我应该如何做呢?
      

  5.   

    lock(obj) 

      // 

    如上面的调面模式中,这个obj,即信号量我在哪定义呀?在主调数中?好像不行呀
      

  6.   

    lock(hastable)
    {
    ....dosomething
    }
      

  7.   

    现在问题是这个类中有多个hashTable(五个),这时我不能一个一个加锁吧?而且我在函数中,对这个函数的执行体,调用hashtable的时候,都按
    lock(hashtable)
    {
    }lock(hashtable1)
    {
    }lock(hashtable2)
    {
    }
    ..
    这样加了锁,可没用.