making observablecollection thread safe

//as a field in class where OC is instantiated:
using System.Collections.ObjectModel; 	//for ObservableCollection<T>
using System.Windows.Data;				//for BindingOperations
using System.Windows;					//for Application
using System.Threading;					//for Dispatcher

public static object m_lockObject;		//NOTE: One lockObject per collection!
public static ObservableCollection<T> m_OC;

//where OC is created (typically the constructor)
OC = new ObservableCollection<T>();
BindingOperations.EnableCollectionSynchronization(m_OC, m_lockObject);
Application.Current.Dispatcher.Send(
  		DispatcherPriority.Background,
  		new Action(() => {
        BindingOperations.EnableCollectionSynchronization(m_OC, m_lockObject);
		}));
//the call of EnableCollectionSynchronization MUST happen on the UI thread.
//This Dispatcher action ensures that it does.

//-- FINALLY --
//when altering OC will trigger OnPropertyChanged (.Add(), .Clear(), etc.)
//encase such statements within a lock using that OC's lockObject
lock (m_lockObject)
{
  m_OC.Add(null);
}


//ALTERNATE SOLUTION: do any alterations to the OC on the Dispatcher thread
Application.Current?.Dispatcher?.Invoke(() =>
{
	//Do stuff
});

Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source