WPF 在另一个线程中清除 ObservableCollection
WPF clear ObservableCollection in another thread
我在 WPF 中有应用程序,我想在从另一个线程设置 setter 时清除 ObservableCollection。
这是setter:
public List<Model.MasterReview> SelectedMasterReviews
{
get { return selectedMasterReviews; }
set
{
selectedChildReview = null;
selectedMasterReviews = value;
Application.Current.Dispatcher.Invoke((Action)delegate
{
GetChildReviews();
});
}
}
private void GetChildReviews()
{
Application.Current.Dispatcher.Invoke((Action)delegate
{
ChildReviews.Clear();
});
}
然后出现错误:
This type of CollectionView does not support changes to its SourceCollection from a thread
different from the Dispatcher thread
这段代码给我同样的错误:
var uiContext = SynchronizationContext.Current;
uiContext.Send(x => ChildReviews.Clear(), null);
我已经解决了这个问题。
第一次在另一个线程中清除 ChildReviews:
Task.Run(() => Application.Current.Dispatcher.Invoke((Action)delegate
{
GetChildReviews();
}); )
然后在另一个分发器中:
Application.Current.Dispatcher.Invoke((Action)delegate
{
GetChildReviews();
});
我不得不删除 Task.Run()
,现在可以使用了
我在 WPF 中有应用程序,我想在从另一个线程设置 setter 时清除 ObservableCollection。
这是setter:
public List<Model.MasterReview> SelectedMasterReviews
{
get { return selectedMasterReviews; }
set
{
selectedChildReview = null;
selectedMasterReviews = value;
Application.Current.Dispatcher.Invoke((Action)delegate
{
GetChildReviews();
});
}
}
private void GetChildReviews()
{
Application.Current.Dispatcher.Invoke((Action)delegate
{
ChildReviews.Clear();
});
}
然后出现错误:
This type of CollectionView does not support changes to its SourceCollection from a thread
different from the Dispatcher thread
这段代码给我同样的错误:
var uiContext = SynchronizationContext.Current;
uiContext.Send(x => ChildReviews.Clear(), null);
我已经解决了这个问题。 第一次在另一个线程中清除 ChildReviews:
Task.Run(() => Application.Current.Dispatcher.Invoke((Action)delegate
{
GetChildReviews();
}); )
然后在另一个分发器中:
Application.Current.Dispatcher.Invoke((Action)delegate
{
GetChildReviews();
});
我不得不删除 Task.Run()
,现在可以使用了