mzl9039
mzl9039

Reputation: 1

multithread Error .net Parallel.For

I have to caculate distances among about 26,000 companies, and to find the median of all the distances. However, the program throw the exception below:

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()

This is my program:

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>

Upvotes: 0

Views: 113

Answers (1)

Vadim Martynov
Vadim Martynov

Reputation: 8892

You call ConcurrentDictionary<TKey, TValue>.Item which can throw KeyNotFoundException if the property is retrieved and key does not exist in the collection.

Change you code to ensure that elements are exist in the dictionary:

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++;
}

Upvotes: 0

Related Questions