My code like that.
List<MyPanel> list_panel = new List<MyPanel>();
.......
List<string> list_sql = new List<string>();
Parallel.For(0, list_panel.Count, i =>
{
if (list_panel[i].R == 0)
{
list_sql.AddRange(list_panel[i].MakeSqlForSave()); // it returns two string
}
});
But AddRange occur System.ArgumentException sometimes.
I found 'list isn't for multi write'. So I fix it using lock.
string[] listLock = new string[2];
Parallel.For(0, list_panel.Count, i =>
{
if (list_panel[i].R == 0)
{
listLock = list_panel[i].MakeSqlForSave();
lock(listLock)
list_sql.AddRange(listLock);
}
});
But it still occur System.ArgumentException that 'Source array was not long enough. Check srcIndex and length, and the array's lower bounds.' sometimes.
An error occurred in list_sql. If the count is 34, but the IndexOfRangeException occurs when you call list_sql[32] and list_sql[33].
How can I handle it?
List<T>(and especiallyList<T>.AddRange) is not thread-safe.lock()statement is incorrect because it locks on a thread-local object rather than a shared object.MyPanela WinForms control? If so, this code is unsafe because WinForms controls should only be accessed from the GUI thread.