I have a DataGridView with its source set to BindingSource, whose source is set to BindingList that cotains objects that implement INotifyPropertyChanged. The problem is, the logic that updates items in my BindingList runs in a separate thread. Everything is absolutely fine, but I’m not sure why it works at all. Is there any logic in any of these to handle cross-thread access? What’s the right approach in this case?
BindingSource _actionsBindingSource; // it's DGV's source
BindingList<IAction> _actionsList = ...;
...
interface IAction : INotifyPropertyChanged
{
...
}
...
actionsBindingSource.DataSource = _actionsList;
...
public void FireActions()
{
new Thread(() =>
{
foreach (IAction action in _actionsList)
{
action.Execute(); // fires some PropertyChangedEventArgs events from non-UI thread
}
}).Start();
}
So, I’m curious about my FireActions() method.
I would suggest you to run your code in the UI Thread instead of using another thread. The issue that when data are changing the binding source, it ultimately changes the blinding control. Therefore you need to load the data to using the UI Thread and not a worker thread.
An example would be a BindingSource links to a DataTable, and a DataGrid binds to the BindingSource. You may think why not use a worker thread to load the data to the DataTable, which would avoid locking the UI Thread. However, this wouldn’t work because BindingSource ultimately need to update your DataGrid, which is an UI operation.