C# 多线程错误.net并行.For
我必须计算大约26000家公司之间的距离,并找到所有距离的中位数。但是,程序会引发以下异常:C# 多线程错误.net并行.For,c#,multithreading,parallel.for,C#,Multithreading,Parallel.for,我必须计算大约26000家公司之间的距离,并找到所有距离的中位数。但是,程序会引发以下异常: at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions) at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken) at System.Thre
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);
}
}
protectedvoid CountDistancesPerKilometer()
{
尝试
{
int EnterprisesCount=enterprises.Count;
秒表=新秒表();
watch.Start();
Parallel.For(0,enterprises.Count,(i,loopStateOut)=>
{
企业出口=企业。元素(i);
对于(int j=i+1;j
附言:
企业:列表
距离文件:ConcurrentDictionary
如果检索到属性且集合中不存在键,则调用可以抛出的
更改代码以确保字典中存在元素:
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++;
}
距离文件[(int)距离].FileRowCount++-您确定
distance
是字典中的现有键吗?什么是DistanceFiles
?@DmitryBychenko在问题的底部:ConcurrentDictionary
您的代码的顺序版本(即Parallel.For
更改为For(…)
)@mzl9039请添加完整的异常信息,包括内部异常详细信息。更改日志写入错误(例如StackTrace);到Log.WriteError(例如ToString());或Log.WriteError(例如Message);我不能保证所有公司的职位都是正确的,所以你的答案可能是正确的!我会试试的,非常感谢@瓦迪姆·马丁诺夫
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++;
}