+2  A: 

Where you've got code which adds the item to the observable collection (presumably in the view model), wrap that Add call in a Dispatcher.BeginInvoke call.

Admittedly that means the view model needs to know about the dispatcher, which then becomes awkward to test... fortunately it's not too hard to introduce your own IDispatcher interface and use dependency injection in the normal way.

Jon Skeet
Hi Jon, Thanks for your reply, I Already have a collection object, which Inherits from ObserveableCollection on InsertItem this does Dispatcher.CheckAccess if false then does Dispather.BeginInvoke, however this is still not working??
jpgooner
@jpgooner: Are you sure that code is actually being used? Can you come up with a short but complete example which demonstrates the problem?
Jon Skeet
@Jon Skeet: I have added more detail above, let me know if you need anymore, I am still new to stackoverflow
jpgooner
@Jon Skeet, figured it out thanks to your response, because the background thread was creating some on the collections check access was returning true, when inactual fact i needed to compare to the UI thread! Thank for your help!
jpgooner
+1  A: 

How about this?

public class ThreadSafeObservableCollection<T> : ObservableCollection<T>
{
    private SynchronizationContext SynchronizationContext;

    public ThreadSafeObservableCollection()
    {
        SynchronizationContext = SynchronizationContext.Current;

        // current synchronization context will be null if we're not in UI Thread
        if (SynchronizationContext == null)
            throw new InvalidOperationException("This collection must be instantiated from UI Thread, if not, you have to pass SynchronizationContext to con                                structor.");
    }

    public ThreadSafeObservableCollection(SynchronizationContext synchronizationContext)
    {
        if (synchronizationContext == null)
            throw new ArgumentNullException("synchronizationContext");

        this.SynchronizationContext = synchronizationContext;
    }

    protected override void ClearItems()
    {
        this.SynchronizationContext.Send(new SendOrPostCallback((param) => base.ClearItems()), null);
    }

    protected override void InsertItem(int index, T item)
    {
        this.SynchronizationContext.Send(new SendOrPostCallback((param) => base.InsertItem(index, item)), null);
    }

    protected override void RemoveItem(int index)
    {
        this.SynchronizationContext.Send(new SendOrPostCallback((param) => base.RemoveItem(index)), null);
    }

    protected override void SetItem(int index, T item)
    {
        this.SynchronizationContext.Send(new SendOrPostCallback((param) => base.SetItem(index, item)), null);
    }

    protected override void MoveItem(int oldIndex, int newIndex)
    {
        this.SynchronizationContext.Send(new SendOrPostCallback((param) => base.MoveItem(oldIndex, newIndex)), null);
    }
}
Brent Beardsley
+1  A: 

I found a blog post that uses the Dispatcher to manage all of the ObeservableCollection's methods. Here is a snip-it of the code, see the post for the entire class.

public class DispatchingObservableCollection<T> : ObservableCollection<T>
{
    /// <summary>
    /// The default constructor of the ObservableCollection
    /// </summary>
    public DispatchingObservableCollection()
    {
        //Assign the current Dispatcher (owner of the collection)
        _currentDispatcher = Dispatcher.CurrentDispatcher;
    }

    private readonly Dispatcher _currentDispatcher;

    /// <summary>
    /// Executes this action in the right thread
    /// </summary>
    ///<param name="action">The action which should be executed</param>
    private void DoDispatchedAction(Action action)
    {
        if (_currentDispatcher.CheckAccess())
            action.Invoke();
        else
            _currentDispatcher.Invoke(DispatcherPriority.DataBind, action);
    }

    /// <summary>
    /// Clears all items
    /// </summary>
    protected override void ClearItems()
    {
        DoDispatchedAction(BaseClearItems);
    }

    private void BaseClearItems()
    {
        base.ClearItems();
    }

    /// <summary>
    /// Inserts a item at the specified index
    /// </summary>
    ///<param name="index">The index where the item should be inserted</param>
    ///<param name="item">The item which should be inserted</param>
    protected override void InsertItem(int index, T item)
    {
        DoDispatchedAction(() => BaseInsertItem(index, item));
    }
chilltemp