0

And is there any danger to making my own INotifyCollectionChanged implementation that doesn't?

I'm trying to make a class library contains a Log class, which in turns contains some sort of observable collection. But if I try to actually add anything to the log from anywhere but the UI thread, the app crashes saying I'm not allowed to do that. Is there any reason .NET is designed that way? Can I work around it without causing horrible things to happen?

2 Answers 2

4

This has nothing to do with ObservableCollection and everything to do with WPF.

WPF requires all changes to be done on the UI thread. But WPF doesn't dispatch the changes onto UI thread when collection changes, unlike with property change.

You can work around it either by dispatching the collection change onto UI thread using WPF's Dispatcher. Or you can create a wrapper collection that will dispatch changes of a collection it wraps around.

3
  • What changes specifically have to be done on the UI thread? My ObservableCollection is located in the class library; why would WPF require that changes to that collection be made on the UI thread when it doesn't even own the collection? I'm not even making the changes directly from WPF; I'm making them from elsewhere in the class library, though of course the class library is called from my WPF project. It seems like WPF is polluting my class library with this requirement, which seems totally backwards...
    – ekolis
    Feb 13, 2016 at 16:25
  • @ekolis Do you know how events and threading works?
    – Euphoric
    Feb 13, 2016 at 20:16
  • A little bit, I suppose?
    – ekolis
    Feb 20, 2016 at 10:42
0

You can use this code snippet (Dispatcher + Lambda). Everything in the brackets will be dispatched to the UI thread

Application.Current.Dispatcher.BeginInvoke(() => 
{ 
   add your code here 
});
1
  • 1
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Jun 30, 2023 at 23:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.