【问题标题】:get item[i] from a listview using threads使用线程从列表视图中获取项目 [i]
【发布时间】:2012-04-28 09:48:19
【问题描述】:

我有这样的功能:

foreach (ListViewItem item in getListViewItems(listView2)) //for proxy
{
    if (reader.Peek() == -1)
    {
        break;
    }

    lock (reader)
    {
        line = reader.ReadLine();
    }


    //proxy code
    List<string> mylist = new List<string>();
    if (item != null)
    {
        for (int s = 0; s < 3; s++)
        {
            if (item.SubItems[s].Text != null)
            {
                mylist.Add(item.SubItems[s].Text);
            }
            else
            {
                mylist.Add("");
            }
        }
    }
    else
    {
        break;
    }
    //end proxy code


    //some other code including the threadpool
}

和委托代码:

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.CheckedItems)
        {
            temp.Add((ListViewItem)item.Clone());
        }
        return temp;
    }
    else
    {
       return (ListView.ListViewItemCollection)this.Invoke(new GetItems(getListViewItems), new object[] { lstview });
    }
}

编辑:

我想用条件函数替换主函数中的 foreach 循环:

if (reader.Peek() == -1)
{
    break;
}

lock (reader)
{
    line = reader.ReadLine();
}


if (use_proxy == true)
{
    mylist2 = get_current_proxy();
}

//some other code including the threadpool

private List<string> get_current_proxy()
{
    //what shall I add here?
}

如何使该函数执行与 foreach 循环相同但使用 for 循环的功能?我的意思是一一获取代理...

【问题讨论】:

    标签: c# winforms multithreading delegates invoke


    【解决方案1】:

    我看到多个问题都围绕着一个想法,即从网站上抓取电子邮件然后发送垃圾邮件。你已经有了非常酷的工具,不需要新的。

    无论如何 - 我不明白你的问题,而且似乎我不是这里唯一的人,但你必须先知道的是:

    当您执行Invoke() 时,让Windows 中的任何东西在多个线程中运行最终都必须同步,这必须等到它全部通过一个线程,而那是一个包含消息循环的线程。因此,您可以尝试从多个线程读取或写入ListView,但要进行每次读取/写入,您必须使用Invoke()(您可能直接尝试过 BAAAAM)并且每个 Invoke() 只有一个孔要通过,您的所有线程都必须等待轮到它们。

    下一步:让 ListView 成为您数据的 CONTAINER 太糟糕了,我什至无法进一步评论。将某事视为

    class MyData
    {
        public string Name;
        public string URL;
        // ...
    }
    

    List<MyData> _myData;
    

    保存您的数据。如果您处理一些低调的同步问题,您将能够从多个线程访问它。

    最后,如果你连语法都不知道,你怎么会问我们关于 .net C# 编程的问题。嗯,这是修辞,...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      相关资源
      最近更新 更多