我有一个这样的函数,它使用非线程安全的集合列表,也是线程安全的,它使用锁操作符:
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();
}
我想将它转换为无锁。为此,我在这个函数中使用了 ConcurrentDictionary 集合而不是 List 集合,所以我的函数开始看起来是这样的:
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)?如何解决我的错误?