views:

699

answers:

2

I'm writing a class for logging events. My LogClass is implemented as a singleton, and any class in the system can write a log entry. The entries are stored in a List and when a buffer is filled they get dumped to the disk.

I'm using a DataGridView to display the contents of the LogClass during execution, therefore I used the BindingList so that the Viewer would update automatically.

I'm wondering how thread safe my class is. I'm using "lock" everytime I add a new entry to the list, and when I'm iterating through the list to dump it to the disk. Besides the DataGridView, the class is basically Write-Only because there isn't an option to read from the log, only to add entrires to the log. The dump is executed internally, and that is the only time there is a explicit read command on the BindingList.

So my real concern is what goes on with the DataGridView and the BindingList ? The BindingList throws an event everytime the list changes. This doesnt seem like a concern when adding new entries, because the event is thrown when the adding finished.

My code for Dump() is:

lock (lockObj) {
    foreach (LogEntry le in List) {
      writeToDisk(le)
      removeFromList(le)
    }
 }

Even though I'm locking the list during the whole iteration, an event is thrown to the Viewer that the list changed (because of the removal) and therefore being read by the DataGridView. I don't really want anything reading/writing to the list while I'm altering it. Any ideas?

A: 

I thought that BindingList didn't implement change notification. In this scenario I don't think this is thread safe.

The solution might be to use custom collection that implements IBindingList and change the list accessor to acquire lock before returning any element.

I have a custom implementation of IBindingList with change notification so if you want I can share this.(I'll probably write an article on code project describing the implementation anyway..)

kubal5003
+1  A: 

It's not really a concern because, once bound, you can only change the list from the Form.Invoke method (inherited from Control.Invoke). If you try to change the list from another thread, the .NET runtime will bark at your w/ an exception saying something to the effect of "can't change this list from current thread".

This has some code you can grab.

Regards, =Alan

Alan