BindingSource、BindingList、DataGridView 和跨线程访问

发布于 2024-12-20 16:17:39 字数 769 浏览 1 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

水溶 2024-12-27 16:17:39

我建议您在 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文