I have such structure MainWindow
where I call this method AddTaskBtnClicked
from other class
partial class MainWindow: Window
{
...
private void foo()
{
m_presenter.AddTaskBtnClicked();
}
...
}
then my Presenter
public class Presenter{
...
public ObservableCollection<string> TaskList { get; } = new ...;
public void AddTaskBtnClicked() =>
FactoryTask?.StartNew(() =>
{
TaskList.Add(...);
}
...
And here in this line TaskList.Add(...);
I get an error
System.NotSupportedException: 'This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread.'
I understand that I can move this line in UI thread or don't call StartNew()
, but problem is that I can't change it. I need somehow make it work, maybe with use of dispatcher. I found this answer on SO
https://stackoverflow.com/a/33343937/5709159
But problem is that all of these BindingOperations.EnableCollectionSynchronization
, var uiContext = SynchronizationContext.Current;
or Dispatcher.Invoke
works just in class that inharite from UI (UserControl or Window).
So, question is - how to add item in Observable collection from other thread in class that doesn't inherit form UI ?