多线程错误.net Parallel.For

时间:2016-03-28 11:04:20

标签: c# multithreading parallel.for

我必须计算大约26,000家公司之间的距离,并找出所有距离的中位数。但是,该程序抛出以下异常:

at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at System.Threading.Tasks.Task.Wait()
at System.Threading.Tasks.Parallel.ForWorker[TLocal](Int32 fromInclusive, Int32 toExclusive, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Func`4 bodyWithLocal, Func`1 localInit, Action`1 localFinally)
at System.Threading.Tasks.Parallel.For(Int32 fromInclusive, Int32 toExclusive, Action`2 body)
at DataHelper.FindMediumBase.CountDistancesPerKilometer()

这是我的计划:

protected void CountDistancesPerKilometer()
{
    try
    {
        int EnterprisesCount = enterprises.Count;
        Stopwatch watch = new Stopwatch();
        watch.Start();
        Parallel.For(0, enterprises.Count, (i, loopStateOut) =>
        {
            Enterprise eOut = enterprises.ElementAt(i);
            for (int j = i + 1; j < enterprises.Count; j++)
            {
                Enterprise eIn = enterprises.ElementAt(j);
                double distance = Math.Sqrt((eOut.Point.X - eIn.Point.X) * (eOut.Point.X - eIn.Point.X) +
                                            (eOut.Point.Y - eIn.Point.Y) * (eOut.Point.Y - eIn.Point.Y)) / 1000;

                if (0 == distance)
                    continue;
                else
                    DistanceFiles[(int)distance].FileRowCount++;
            }
        });
        watch.Stop();
        System.Console.WriteLine(watch.ElapsedTicks);
    }
    catch (Exception ex)
    {
        Log.WriteError(ex.StackTrace);
    }
}

PS:

enterprises: List<Enterprise>
DistanceFiles : ConcurrentDictionary<int, DistanceFile>

1 个答案:

答案 0 :(得分:0)

如果检索到该属性并且该集合中不存在密钥,则调用ConcurrentDictionary<TKey, TValue>.Item可以抛出KeyNotFoundException

更改代码以确保字典中存在元素:

if (0 == distance)
    continue;
else
{
    if(!DistanceFiles.ContainsKey((int)distance))
    {
        var distanceFile = GetDistanceFile(); // retrieve or create new instance of tDistanceFile here
        DistanceFiles,Add((int)distance, distanceFile);
    }
    DistanceFiles[(int)distance].FileRowCount++;
}