【问题标题】:Can't get items in a ListView cross-thread无法在 ListView 跨线程中获取项目
【发布时间】:2011-11-05 19:49:25
【问题描述】:

我的background worker 需要遍历ListView 中的每个项目。但是我不能这样做:

foreach (ListViewItem Item in List.Items)

因为这是一个跨线程操作。

我也无法将这些项目放入ListView.ListViewItemCollection 并让后台工作人员从中读取。这仍在尝试访问ListView并创建跨线程操作。

如何使ListView 的项目对后台工作人员可用,而不将它们放在某个变量中?

【问题讨论】:

  • 有一种方法可以禁用非法跨线程操作检查,但确切的解决方案是将数据放入数据访问对象或变量中,并在后台操作完成时更新列表视图。

标签: c# listview thread-safety backgroundworker


【解决方案1】:

尝试使用此功能。

private delegate ListView.ListViewItemCollection GetItems(ListView lstview);

private ListView.ListViewItemCollection getListViewItems(ListView lstview)
{
    ListView.ListViewItemCollection temp = new ListView.ListViewItemCollection(new ListView());
    if (!lstview.InvokeRequired)
    {
        foreach (ListViewItem item in lstview.Items)
        temp.Add((ListViewItem)item.Clone());
        return temp;
    }
    else
        return (ListView.ListViewItemCollection)this.Invoke(new GetItems(getListViewItems), new object[] { lstview });
}

这样称呼它:

foreach(ListViewItem item in getListViewItems(List))

【讨论】:

    【解决方案2】:

    我同意mdb,但不得不提的是,根据应用的重要性,

    Control.CheckForIllegalCrossThreadCalls = false;

    仍然可以用作临时快速修复。

    【讨论】:

      【解决方案3】:

      试试这个。

      public Form1()
      {
          InitializeComponent();
      
          Control.CheckForIllegalCrossThreadCalls = false;
      }
      

      【讨论】:

      • 这是个坏建议。尽管它会消除错误消息,但您仍然会在没有任何同步的情况下进行跨线程调用,这可能会破坏您的结果。正确答案涉及使用委托,如另一个答复中所述。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-27
      • 1970-01-01
      • 2010-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多