[ACCEPTED]-ObservableCollection and threading-observablecollection

Accepted answer
Score: 16

The best way to solve this is to pass the 10 Dispatcher object to the start method of the background 9 thread.

void DoBackgroundOperation(ObservableCollection<SomeType> col) {
  var dispatcher = Dispatcher.CurrentDispatcher;
  ThreadStart start = () => BackgroundStart(dispatcher, col);
  var t = new Thread(start);
  t.Start();
}

private static void BackgroundStart(
    Dispatcher dispatcher, 
    ObservableCollection<SomeType> col) {
  ...
  SomeType t = GetSomeTypeObject();
  Action del = () => col.Add(t);
  dispatcher.Invoke(del);
}

Now later on when you need to add 8 to the collection you can use the UI Dispatcher object.

As 7 @Reed pointed out, a more general solution 6 is achieved by using SynchronizationContext. Here's a functional 5 style sample using SynchronizationContext to create a delegate 4 responsible for adding new values. This 3 has the advantage of hiding both the collection 2 and the threading model from the code creating 1 the object.

void DoBackgroundOperation(ObservableCollection<SomeType> col) {
  var context = SynchronizationContext.Current;
  Action<SomeType> addFunc = (SomeType st) => context.Send(() => col.Add(st), null);
  ThreadStart start = () => BackgroundStart(addFunc);
  var t = new Thread(start);
  t.Start();
}

private static void BackgroundStart(Action<SomeType> addFunc) {
  ...
  SomeType t = GetSomeTypeObject();
  addFunc(t);
}
Score: 15

JaredPar's approach is a valid one. Another 7 approach which is worth considering is using 6 a thread safe ObservableCollection instead of the built-in ObservableCollection. There's 5 a few implementations out there, but Sasha Barber's implementation and 4 the CLinq Continuous Collection class are some of the better ones in my opinion. Internally, these 3 classes essentially use the approach outlined 2 by JaredPar, but encapsulate it inside the 1 collection class.

Score: 6

In.Net 4.5, you can use the Thread-safe 3 collections, ConcurrentDictionary, ConcurrentBag 2 etc, whichever suits your needs : http://msdn.microsoft.com/en-us/library/dd997305.aspx

Please 1 consider reading also : http://www.codeproject.com/Articles/208361/Concurrent-Observable-Collection-Dictionary-and-So

More Related questions