【问题标题】:Get the items in a ListView in thread via a class通过类获取线程中ListView中的项目
【发布时间】:2014-01-26 05:25:36
【问题描述】:

我有一个类,我有一个函数“Build”,该类有一个参数:“ListView lstFiles”。当 .Build 被调用时,它会遍历列表视图中的每个项目并对其进行处理。

当我尝试这样做时,我收到错误“跨线程访问冲突”

我的代码:

foreach (ListViewItem item in lstFiles.Items)
{
    // Processing here
}

我尝试获取这里描述的项目http://msdn.microsoft.com/en-us/library/ms171728%28VS.80%29.aspx

我需要获取 ListView 中的每一项并对其进行处理

有人可以帮忙吗?

【问题讨论】:

  • 代码是如何被触发的?这段代码是从您之前创建的另一个线程执行的吗?
  • 这段代码被一个类(一个单独的类)触发。

标签: c# .net multithreading exception


【解决方案1】:

使用委托解决跨线程问题。例如

    delegate ListView.ListViewItemCollection DelGetItems(ListView lvControl);

    ListView.ListViewItemCollection GetItems(ListView lvControl)
    {
        if (lvControl.InvokeRequired)
        {
            return (ListView.ListViewItemCollection)lvControl.Invoke(new DelGetItems(GetItems) ,new Object[] { lvControl });
        }
        else
        {
            return lvControl.Items;
        }
    }

【讨论】:

  • 我调整了你的代码(因为我不能使用“this.Invoke”),仍然得到一个空值。请记住,我正在使用一个类,然后调用 Build 方法。该类有一个构造函数,它将 ListView 的名称作为参数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多