【问题标题】:Multi-threading -- Updating a listview in C#多线程——在 C# 中更新列表视图
【发布时间】:2013-06-18 21:48:06
【问题描述】:

我正在尝试在处理文本文件的 Windows 窗体应用程序中更新我的列表视图来更新控件。我的问题与跨线程有关;每当我尝试更新控件时,都会出现错误。在我对应用程序进行多线程处理之前没有错误,但是 UI 只会在处理完整个文本文件后更新。我希望在读取每一行后更新 UI。

我已经发布了相关代码,希望有人可以给我一些提示,因为我现在在墙上。在 UpdateListView 方法中的 if 语句期间发生错误。请注意,PingServer 方法是我编写的,与我的问题无关。

    private void rfshBtn_Click(object sender, EventArgs e)
    {
        string line;
        // Read the file and display it line by line.
        var file = new StreamReader("C:\\Users\\nnicolini\\Documents\\Crestron\\Virtual Machine Servers\\servers.txt");
        while ((line = file.ReadLine()) != null)
        {
            Tuple<string, string> response = PingServer(line);
            Thread updateThread = new Thread(() => { UpdateListView(line, response.Item1, response.Item2); });
            updateThread.Start();
            while (!updateThread.IsAlive) ;
            Thread.Sleep(1);
        }
        file.Close();
    }

    private void UpdateListView(string host, string tries, string stat)
    {
        if (!listView1.Items.ContainsKey(host)) //if server is not already in listview
        {
            var item = new ListViewItem(new[] { host, tries, stat });
            item.Name = host;
            listView1.Items.Add(item); //add it to the table
        }
        else //update the row
        {
            listView1.Items.Find(host, false).FirstOrDefault().SubItems[0].Text = host;
            listView1.Items.Find(host, false).FirstOrDefault().SubItems[1].Text = tries;
            listView1.Items.Find(host, false).FirstOrDefault().SubItems[2].Text = stat;
        }
    }

【问题讨论】:

标签: c# .net multithreading winforms listview


【解决方案1】:

Winform 组件只能从主线程更新。如果要从其他线程进行更新,应在主线程上使用component.BeginInvoke() 调用更新代码。

代替

 listView1.Items.Add(item);

你可以这样写:

listView1.BeginInvoke(() => listView1.Items.Add(item));

如果您的线程只进行 UI 更新而不进行其他资源密集型操作,那么完全不使用它并从主线程调用 UpdateListView 作为方法是合理的。

【讨论】:

  • 你能说得更具体点吗?我尝试在 UpdateListView 方法中调用,但我遇到了同样的错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-22
  • 2019-01-19
  • 2021-04-30
相关资源
最近更新 更多