BindingSource、BindingList、DataGridView 和跨线程访问
我有一个 DataGridView
,其源设置为 BindingSource
,其源设置为 BindingList
,其中包含实现 INotifyPropertyChanged
的对象>。问题是,更新 BindingList
中的项目的逻辑在单独的线程中运行。一切都很好,但我不确定为什么它会起作用。其中是否有处理跨线程访问的逻辑?在这种情况下,正确的做法是什么?
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();
}
所以,我对我的 FireActions()
方法很好奇。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我建议您在 UI 线程中运行代码,而不是使用另一个线程。当数据改变绑定源时,最终会改变致盲控制的问题。因此,您需要使用 UI 线程而不是工作线程加载数据。
一个示例是 BindingSource 链接到 DataTable,DataGrid 绑定到 BindingSource。您可能会想为什么不使用工作线程将数据加载到 DataTable,这样可以避免锁定 UI 线程。但是,这不起作用,因为 BindingSource 最终需要更新 DataGrid,这是一个 UI 操作。
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.