我最近不得不重写一个控制台应用程序来处理新的Mono设置(Mono的更新版本),而我之前使用的代码不再按预期方式工作。请考虑以下事项:
List<Device> devices = db_device.get();
List<Profile> profiles = db_mib.load_profiles();
List<Task> tasks = new List<Task>();
int count=0;
foreach(Device device in devices)
{
tasks.Add(new Task((obj) =>
{
Device dev = null;
try
{
dev = (Device)obj;
// search profiles for a list of all profiles.
foreach(Profile profile in profiles)
{
if(profile.id == dev.deviceType)
{
// clone the profile and assign the mibs to the device
Profile temp = (Profile)profile.Clone();
dev.mibs = temp.mibs;
}
}
snmp_get(dev);
snmp_walk(dev);
rrd_get(dev);
rrd_walk(dev);
}
catch(KeyNotFoundException exp)
{
write_exception("KeyNotFoundException", dev, exp, "Caught in Main");
}
catch(NullReferenceException exp)
{
write_exception("NullReferenceException", dev, exp, "Caught in Main");
}
catch(AggregateException exp)
{
write_exception("AggregateException", dev, exp, "Caught in Main");
}
catch(ArgumentOutOfRangeException exp)
{
write_exception("ArgumentOutOfRangeException", dev, exp, "Caught in Main");
}
catch(RRDCommandException exp)
{}
}, device));
tasks[count++].Start();
}
Task.WaitAll(tasks.ToArray());
Console.WriteLine("All tasks finished.");
// some more code that must run only once all tasks have finished
在我之前的设置中,我可以完成“所有任务已完成”。但是,我不再达到这一点。任务运行并返回结果,但似乎WaitAll永远不会认为任务完成。我做了一些研究,人们建议使用Task.Run而不是Task.Start。尽管在创建任务时需要调用它,而不是之后需要调用它,但我仍然难以绕过需要做的事情。非常感谢任何帮助。