From ea43e2a72dcfea423b2c95adbd030291231b12c1 Mon Sep 17 00:00:00 2001 From: Gang Zhuo Date: Thu, 25 Feb 2016 22:41:20 +0800 Subject: [PATCH] use ConcurrentDictionary instead of Dictionary --- shadowsocks-csharp/Encryption/IVEncryptor.cs | 25 +++++++------------- 1 file changed, 9 insertions(+), 16 deletions(-) diff --git a/shadowsocks-csharp/Encryption/IVEncryptor.cs b/shadowsocks-csharp/Encryption/IVEncryptor.cs index f1922ac0..6d84de56 100755 --- a/shadowsocks-csharp/Encryption/IVEncryptor.cs +++ b/shadowsocks-csharp/Encryption/IVEncryptor.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Collections.Concurrent; using System.Security.Cryptography; using System.Text; using System.Net; @@ -24,7 +25,7 @@ namespace Shadowsocks.Encryption protected Dictionary ciphers; - private static readonly Dictionary CachedKeys = new Dictionary(); + private static readonly ConcurrentDictionary CachedKeys = new ConcurrentDictionary(); protected byte[] _encryptIV; protected byte[] _decryptIV; protected bool _decryptIVReceived; @@ -62,22 +63,14 @@ namespace Shadowsocks.Encryption } keyLen = ciphers[_method][0]; ivLen = ciphers[_method][1]; - if (!CachedKeys.ContainsKey(k)) + _key = CachedKeys.GetOrAdd(k, (nk) => { - lock (CachedKeys) - { - if (!CachedKeys.ContainsKey(k)) - { - byte[] passbuf = Encoding.UTF8.GetBytes(password); - _key = new byte[32]; - byte[] iv = new byte[16]; - bytesToKey(passbuf, _key); - CachedKeys[k] = _key; - } - } - } - if (_key == null) - _key = CachedKeys[k]; + byte[] passbuf = Encoding.UTF8.GetBytes(password); + byte[] key = new byte[32]; + byte[] iv = new byte[16]; + bytesToKey(passbuf, key); + return key; + }); } protected void bytesToKey(byte[] password, byte[] key)