To MSFT Engineers - others. Help understand Collection Behavior

J

JimGreen

Hello All
I need some help in understanding some .NET behavior.
I created a collection class derived from CollectionBase and
IBindingList.
I bound a datagrid to the collection.
I added a button and on the click I called RemoveAt(0) . The grid gets
updated properly ( as I am firing ListChanged event from
OnRemoveComplete override of CollectionBase).


Next I created a thread and tried to call myColl.RemoveAt(0) from the
thread, I sometimes get an exception while the datagrid is tring to
paint. It seems as if the removal notice is received by Datagrid after
it tries to paint an item that was already removed .
I don't see any such problems if I says myColl.RemoveAt(
myColl.Count-1).

Any help would be appreciated.
 
J

Jon Skeet [C# MVP]

JimGreen said:
I need some help in understanding some .NET behavior.
I created a collection class derived from CollectionBase and
IBindingList.
I bound a datagrid to the collection.
I added a button and on the click I called RemoveAt(0) . The grid gets
updated properly ( as I am firing ListChanged event from
OnRemoveComplete override of CollectionBase).


Next I created a thread and tried to call myColl.RemoveAt(0) from the
thread, I sometimes get an exception while the datagrid is tring to
paint. It seems as if the removal notice is received by Datagrid after
it tries to paint an item that was already removed .
I don't see any such problems if I says myColl.RemoveAt(
myColl.Count-1).

Any help would be appreciated.

The way I see it, you're changing a bound collection on a different
thread - so the UI is trying to update on that different thread, which
is a bad idea.

I believe you should only update collections which are bound to UI
controls from the UI thread.
 
J

JimGreen

Well that sucks. If I have a collection in the back-end does it mean
that I can update the collection from the background thread as more
data arrives?
If what you are saying is true, then I think MS did not understand user
needs.
 
J

Jon Skeet [C# MVP]

JimGreen said:
Well that sucks. If I have a collection in the back-end does it mean
that I can update the collection from the background thread as more
data arrives?

Not if the collection is bound to the UI, no.
If what you are saying is true, then I think MS did not understand user
needs.

I agree that it makes data binding harder to work with. It's not
generally too hard to marshal the calls which need to update the bound
data to the UI thread though.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top