Thread safety best practices when using DataGridView and BindingList in C #

I am writing a class to register events. My LogClass is implemented as a one-liner and any class on the system can write a log entry. The entries are stored in the List, and when the buffer is full, they are flushed to disk.

I am using a DataGridView to display the content of the LogClass at runtime, so I used a BindingList to have the viewer update automatically.

I am wondering how thread safe my class is. I use "locking" every time I add a new entry to the list, and when I iterate over the list to flush it to disk. Apart from DataGridView, the class is mostly Write-Only because there is no way to read from the log, only to add requests to the log. The dump is done internally, and this is the only time there is an explicit read command in the BindingList.

So my real problem is what is going on with the DataGridView and the BindingList? The BindingList fires an event every time the list changes. This is not a concern when adding new entries, because the event is fired when the addition is complete.

My code for Dump ():

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

      

Even though I am blocking the list during the whole iteration, an event is popping up in the viewer that caused the list to change (due to deletion) and hence the DataGridView was read. I really don't want anything to read / write to the list while I am modifying it. Any ideas?

+2


source to share


2 answers


This is not a concern because after binding, you can only modify the list from the Form.Invoke method (inherited from Control.Invoke). If you try to modify the list from another thread, the .NET runtime will bark at your exception, saying it "cannot modify this list from the current thread."

There is some code in this that you can grab.



Regards, = Alan

+1


source


I thought the BindingList did not follow the change notification. In this case, I don't think it is thread safe.

The solution might be to use a custom collection that implements IBindingList and changes the access to the list to acquire the lock before returning any item.



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

+1


source







All Articles