前提
使用主线程List集合去接收子线程下的元素数据会偶发索引超出了数组的界限 Index was outside the bounds of the array 问题!
例如:
public IList<Dto> GetThreadData()
{
IList<Dto> dt = new List<Dto>();
Task[] tasks = new Task[100];
Task task;
Debug.WriteLine("模仿" + tasks.Length + "次数据接口请求开始:" + DateTime.Now);
for (int i = 0; i < tasks.Length; i++)
{
tasks[i] = new Task(o =>
{
Debug.WriteLine($"子线程ID:{Thread.CurrentThread.ManagedThreadId}");
dt.Add(GetData(Convert.ToInt32(o)));
}, i);
tasks[i].Start();
}
Task.WaitAll(tasks);
Debug.WriteLine($"主线程ID:{Thread.CurrentThread.ManagedThreadId}");
D