多线程列表AddRange

时间:2016-04-27 15:16:47

标签: c# multithreading

问题是TotalRows大约是71800,其中workList只返回718,这只是Task的第一个结果。我有WaitAll,但是第一个任务完成后似乎就完成了。

TotalRows = GetRowCount();
        var lastRecord = 0;
        List<tmpWBITEMALL> workList = new List<tmpWBITEMALL>();
        for (int i = 0; i < 100; i++)
        {
            var tmpI = i;
            gatherTmpTasks.Add(Task.Factory.StartNew(() =>
            {
                var context = new AS400_PIM5ContextDataContext();
                context.CommandTimeout = 0;
                int amount = (TotalRows / 100);
                int tmplastRecord = lastRecord;
                Interlocked.Add(ref lastRecord, amount); 
                Console.WriteLine("Getting rows " + tmplastRecord+ " to " +  (tmplastRecord + amount));
                var pagedResult = context.ExecuteQuery<tmpWBITEMALL>("SELECT * FROM (SELECT ROW_NUMBER() OVER ( ORDER BY Id ) AS RowNum, * from tmpWBITEMALL) AS RowConstrainedResult WHERE   RowNum >= " + tmplastRecord+ " AND RowNum < " + amount + " ORDER BY RowNum");
                lock (listLock)
                    workList.AddRange(pagedResult);
                context.Dispose();
            })); 
        }
        Task.WaitAll(gatherTmpTasks.ToArray());
        Console.WriteLine("total work: " + workList.Count + " tasks: " + gatherTmpTasks.Count); 

因此,作为参考,gatherTmpTasks.Count返回100但是workList.Count仅为718,其中listLock只是一个静态新对象()。如果没有注意到我正在使用LINQ to SQL

任何人都知道为什么我的列表与TotalRows的大小不同?

1 个答案:

答案 0 :(得分:1)

  

“AND RowNum&lt;”+金额:金额总是718,所以你要求查询总是在tmplastRecord和718之间返回东西,而不是在tmplastRecord和tmplastRecord + amount之间。我想你只需要改为“AND RowNum&lt;”+(tmplastRecord + amount)

聪明人