DataBinding to a singleton collection

  • Thread starter Thread starter Torben Frandsen
  • Start date Start date
T

Torben Frandsen

Hi

I have a collection which is updated from two different threads, using the
singleton pattern. The GetInstance method is of course thread safe. Works
nicely.

Now I want the UI to reflect what's going on in the collection, and what's
more obvious than implementing IBindingList and binding a DataGrid to it?

This may not be a good idea after all, since the DataGrid updates only every
now and then, and the form hangs on closing. I suppose this is a thread
safety issue.

Is there something I can do with my collection to make it more databinding
friendly, or should I invoke a method on the UI thread every time a field is
changed? Or is there a third way?

Torben
 
Hi,

A collection is by default not thread safe, if you are enumerating a
collection you cannot add an element to it, it would rise an exception.

Take a look at skeet's singleton implementation to know how to do a thread
safe singleton class.

Of course this has nothing to do with making the collection operations
threadsafe. You have to do this by your own using some locking mechanism.

I would not implement the IBindingList , what I would do in this case is
implement an event in your collection that is risen when a new element is
added to the collection, doing so will allow you to do whatever you want on
the interface.

The form hangs probably cause the worker thread is not done yet.

Hope this help
 
Ignacio said:
A collection is by default not thread safe

I figured as much :-)
Of course this has nothing to do with making the collection operations
threadsafe. You have to do this by your own using some locking
mechanism.

So what you mean is, it's not sufficient to take out a lock whenever an
instance is requested? When else should I take out a lock? When I request an
item? When I change an item? Everywhere?
I would not implement the IBindingList , what I would do in this
case is implement an event in your collection that is risen when a
new element is added to the collection, doing so will allow you to do
whatever you want on the interface.

And in the end I might have to do that. I just wouldn't have thought my
approach was so unusual.

Torben
 
Back
Top