私はスレッドセーフでないコレクション List を使用する関数を持っています。スレッドセーフにするために、lock-operator を使用します。
public void ShowData(ref DataGridView dmRequests, ref DataGridView URL, ref DataGridView dmData, ref DataGridView errorCodes)
{
List<KeyValuePair<string, ulong>> dmReqList = new List<KeyValuePair<string, ulong>>();
List<KeyValuePair<string, ulong>> urlReqList = new List<KeyValuePair<string, ulong>>();
List<KeyValuePair<string, ulong>> dmDataList = new List<KeyValuePair<string, ulong>>();
List<KeyValuePair<string, ulong>> errCodesList = new List<KeyValuePair<string, ulong>>();
lock (m_logStruct.domainName)
{
dmReqList = m_logStruct.domainName.ToList();
}
lock(m_logStruct.URL)
{
urlReqList = m_logStruct.URL.ToList();
}
lock(m_logStruct.domainData)
{
dmDataList = m_logStruct.domainData.ToList();
}
lock(m_logStruct.errorCodes)
{
errCodesList = m_logStruct.errorCodes.ToList();
}
dmRequests.DataSource = dmReqList.OrderBy(x => x.Key).ToList();
URL.DataSource = urlReqList.OrderBy(x => x.Key).ToList();
dmData.DataSource = dmDataList.OrderBy(x => x.Key).ToList();
errorCodes.DataSource = errCodesList.OrderBy(x => x.Key).ToList();
}
ロックフリーに変換したい。それを行うために、List コレクションの代わりにこの関数 ConcurrentDictionary コレクションで使用したので、関数は次のように見え始めます。
public void ShowData(ref DataGridView dmRequests, ref DataGridView URL, ref DataGridView dmData, ref DataGridView errorCodes)
{
try
{
ConcurrentDictionary<string, ulong> dmReqList = new ConcurrentDictionary<string, ulong>();
ConcurrentDictionary<string, ulong> urlReqList = new ConcurrentDictionary<string, ulong>();
ConcurrentDictionary<string, ulong> dmDataList = new ConcurrentDictionary<string, ulong>();
ConcurrentDictionary<string, ulong> errCodesList = new ConcurrentDictionary<string, ulong>();
dmReqList = m_logStruct.domainName;
urlReqList = m_logStruct.URL;
dmDataList = m_logStruct.domainData;
errCodesList = m_logStruct.errorCodes;
dmRequests.DataSource = dmReqList.OrderBy(x => x.Key);
URL.DataSource = urlReqList.OrderBy(x => x.Key).ToList();//I get error here: Index is out of range
dmData.DataSource = dmDataList.OrderBy(x => x.Key).ToList();
errorCodes.DataSource = errCodesList.OrderBy(x => x.Key).ToList();
}
catch(IOException e)
{
MessageBox.Show(e + " Something bad has been occurred here!");
}
}
しかし、この関数では、エラーが発生し始めます(インデックスが範囲外です)。スレッドセーフコレクション(ConcurrentDictionary)を正しく使用するには? エラーを修正するにはどうすればよいですか?