I try to process a method asynchronously adn store the result in an ObservableCollection, but I always get the Error
Must create DependencySource on same Thread as the DependencyObject.
This is my Default Code that I try to use for the operation: The method LoadServiceTasksAsync is called by a button.
public async void LoadServiceTasksAsync(object o)
{
var serviceTasks = await Task.Run(() => repository.GetServiceTasks((string)o));
var serviceTasksViewModels = serviceTasks.Select(m => new ServiceTaskViewModel()
{
OSM = m.OSM,
Priority = "" + m.Priority,
Status = m.Status
});
ServiceTasks = new ObservableCollection<ServiceTaskViewModel>(serviceTasksViewModels);
}
I also have tried to wrap it in a Dispatcher like this:
public async void LoadServiceTasksAsync(object o)
{
var serviceTasks = await Task.Run(() => repository.GetServiceTasks((string)o));
Application.Current.Dispatcher.Invoke(() =>
{
var serviceTasksViewModels = serviceTasks.Select(m => new ServiceTaskViewModel()
{
OSM = m.OSM,
Priority = "" + m.Priority,
Status = m.Status,
});
ServiceTasks = new ObservableCollection<ServiceTaskViewModel>(serviceTasksViewModels);
});
}
I know that I have to create the serviceTaskViewModels in the MainThread but I have no idea how to do that as the serviceTasks are always in another Thread.
EDIT:
var serviceTasks is an IEnumerable<Models.ServiceTask> which are downloaded with a library from a MySQL-Database. The method repository.GetServiceTasks((string)o) itself works fine. So if I execute var serviceTasks = repository.GetServiceTasks((string)o); there are no problems, except the freezing UI.
I also have only one UI Thread.