It seems the ObservableCollection only support add, remove, clear operation from the UI thread, It throw Not Support Exception if it is operated by a NO UI thread. I tried to override methods of ObservableCollection, unfortunatly, I met lots of problems. Any one can provide me a ObservableCollection sample which can be operated by multi-threads? Many thanks!
+4
A:
Using the link provided by Kent, you could use the following code to modify a collection across threads:
while (!Monitor.TryEnter(_lock, 10))
{
DoEvents();
}
try
{
//modify collection
}
finally
{
Monitor.Exit(_lock);
}
If however you're just looking to modify the collection on your original thread you can try using a callback to your UI thread. I normally do something like this:
this.Dispatcher.Invoke(new MyDelegate((myParam) =>
{
this.MyCollection.Add(myParam);
}), state);
Mark Ingram
2008-10-09 12:43:23
By the sounds of the original post, (s)he wants an implementation of ObservableCollection that can be used from any thread without regard for marshalling to the UI thread. Can be very useful in your business layer, for example.Of course, I could have misunderstood the intent of the question...
Kent Boogaart
2008-10-09 12:47:56
Also, Mark, I don't necessarily know if using BeginInvoke is the best idea, because you won't absolutely guarantee the order of items. Invoke() is the way to go.
Bob King
2008-10-09 12:51:03
Updated my answer to reflect both possible answers. Thanks Kent.
Mark Ingram
2008-10-09 12:51:18
@Bob King, I've updated the code. That was a copy + paste from Silverlight which doesn't have an Invoke method.
Mark Ingram
2008-10-09 13:46:45
+2
A:
You've basically got to Invoke or BeginInvoke over to the UI thread to do those operations.
Public Delegate Sub AddItemDelegate(ByVal item As T)
Public Sub AddItem(ByVal item As T)
If Application.Current.Dispatcher.CheckAccess() Then
Me.Add(item)
Else
Application.Current.Dispatcher.Invoke(Threading.DispatcherPriority.Normal, New AddItemDelegate(AddressOf AddItem), item)
End If
End Sub
Bob King
2008-10-09 12:47:23