【发布时间】:2020-05-13 18:01:43
【问题描述】:
我有 3 个不同的 ObservableCollections 绑定到我的视图。我将它们传递给循环编辑它们的函数,我想在我的视图中显示这些集合中所做的每一个更改。
所有绑定都在工作,我唯一的问题是 UI 仅在函数结束时更新,所以我只能在更改后显示这些集合。
有我的功能,它是解决 TSP 问题的 NearestNeighbour 算法的实现,我想在我的视图中打印解决它的每一步。
public int TSP(ObservableCollection<City> VisitedCities, ObservableCollection<Edge> CurrentEdges, ObservableCollection<Edge> FinalEdges)
{
int bestDistance = 0;
City currentCity = cities.First();
cities.RemoveAt(0);
VisitedCities.Add(new City(currentCity.X, currentCity.Y, currentCity.Number));
int minWeight = int.MaxValue;
City tmp = currentCity;
do
{
foreach(City city in cities)
{
if (minWeight > neighbourMatrix[currentCity.Number, city.Number] && neighbourMatrix[currentCity.Number,city.Number] !=0)
{
minWeight = neighbourMatrix[currentCity.Number, city.Number];
tmp = city;
}
CurrentEdges.Add(new Edge(currentCity.X, currentCity.Y, city.X, city.Y, neighbourMatrix[currentCity.Number, city.Number]));
}
FinalEdges.Add(new Edge(currentCity.X, currentCity.Y, tmp.X, tmp.Y, neighbourMatrix[currentCity.Number, tmp.Number]));
bestDistance += neighbourMatrix[currentCity.Number, tmp.Number];
CurrentEdges.Clear();
VisitedCities.Add(new City(tmp.X, tmp.Y, tmp.Number));
currentCity = new City(tmp.X, tmp.Y, tmp.Number);
cities.Remove(tmp);
minWeight = int.MaxValue;
} while (cities.Any());
FinalEdges.Add(new Edge(VisitedCities.Last().X, VisitedCities.Last().Y, VisitedCities.First().X, VisitedCities.First().Y, neighbourMatrix[VisitedCities.Last().Number, VisitedCities.First().Number]));
return bestDistance;
}
我有一个使用ComponentDispatcher 的想法,当我用它替换我的do{...}while() 时它工作得很好,但是你可以看到我需要另一个循环来进行计算。因此,我只能打印当前顶点,以及每一步到下一个顶点的路径。我还想打印当前在foreach(..) 循环中检查的每条边。
有人可以帮我吗?我还想实现 A* 算法和模拟退火,因此解决方案不应仅限于使用该功能。
【问题讨论】:
-
嗨,谢夫,这个代码块在 BackgroundWorker 中运行?如果没有,应该是!
-
您好,感谢您的回答。我不确定如何在这里使用
BackgroundWorker。我正在使用 MVVM 模板,当我想要报告的唯一进度是集合的更改时,我不知道如何使用 BackgroundWorker 报告进度,由于IObserverinterface,它应该自动更改 UI。 -
当我尝试以某种方式使用 BackgroundWorker 时,我得到一个异常,说类型
CollectionView只能从 Dispatcher 线程更改
标签: c# asynchronous observablecollection dispatcher