I created a MAUI application and in the view-model I have an ObservableCollection storing positions. Then these are displayed on the UI on a diagram. But the calculation of the positions takes a lot of time so I do it on another thread to keep the UI unblocked. When I calculate a position I add it to the collection on the new thread by invoking the Application.Current.Dispatcher.Dispatch method, like this:
Task.Run(() =>
{
for (int i = 0; i < 1000; i++)
{
Application.Current.Dispatcher.Dispatch(() =>
{
myObservableCollection.Add(new Pos() { X = i, Y = i }));
}
}
}
It is working perfectly, but i want to avoid the constant thread switching in every iteration so I came up with this:
Task.Run(() =>
{
List<Pos> test = new List<Pos>();
for (int i = 0; i < 1000; i++)
{
test.Add(new Pos() { X = i, Y = i }));
}
Application.Current.Dispatcher.Dispatch(() =>
{
myObservableCollection= new ObservableCollection<Pos>(test);
});
}
So i create the list and only pass it to the observable collection when it is ready to avoid thread switching. But this solution is not updating the UI at all and nothing appears meanwhile the first works perfectly. Why is the second one not working?