`
mlzboy
  • 浏览: 724708 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

SynchronizedDictionary线程安全的泛型版本

 
阅读更多
Code
<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->using System.Collections.Generic;

namespace Amib.Threading.Internal
{
    
internal class SynchronizedDictionary<TKey, TValue>
    {
        
private readonly Dictionary<TKey, TValue> _dictionary;
        
private readonly object _lock;

        
public SynchronizedDictionary()
        {
            _lock 
= new object();
            _dictionary 
= new Dictionary<TKey, TValue>();
        }

        
public int Count
        {
            
get { return _dictionary.Count; }
        }

        
public bool Contains(TKey key)
        {
            
lock (_lock)
            {
                
return _dictionary.ContainsKey(key);
            }
        }

        
public void Remove(TKey key)
        {
            
lock (_lock)
            {
                _dictionary.Remove(key);
            }
        }

        
public object SyncRoot
        {
            
get { return _lock; }
        }

        
public TValue this[TKey key]
        {
            
get
            {
                
lock (_lock)
                {
                    
return _dictionary[key];
                }
            }
            
set
            {
                
lock (_lock)
                {
                    _dictionary[key] 
= value;
                }
            }
        }

        
public Dictionary<TKey, TValue>.KeyCollection Keys
        {
            
get
            {
                
lock (_lock)
                {
                    
return _dictionary.Keys;
                }
            }
        }

        
public Dictionary<TKey, TValue>.ValueCollection Values
        {
            
get
            {
                
lock (_lock)
                {
                    
return _dictionary.Values;
                }
            }
        }
        
public void Clear()
        {
            
lock (_lock)
            {
                _dictionary.Clear();
            }
        }
    }
}

 

非本人原创,所有泛型集合类都是非线程安全的,大家需要自己处理,例子共大家参考吧

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics