C# 线程问题

2023-12-09

我正在做的是从先前的按钮单击动态创建的列表视图。然后 ti 启动一个后台工作程序,其中应清除列表视图并每 30 秒用新信息填充 iistview。
我不断得到: 跨线程操作无效:从创建它的线程以外的线程访问控制“listView 2”。

  private void watcherprocess1Updatelist()
    {
        listView2.Items.Clear();
        string betaFilePath1 = @"C:\Alpha\watch1\watch1config.txt";
        using (FileStream fs = new FileStream(betaFilePath1, FileMode.Open))
        using (StreamReader rdr = new StreamReader((fs)))
        {
            while (!rdr.EndOfStream)
            {
                string[] betaFileLine = rdr.ReadLine().Split(',');
                using (WebClient webClient = new WebClient())
                {
                    string urlstatelevel = betaFileLine[0];
                    string html = webClient.DownloadString(urlstatelevel);
                    File.AppendAllText(@"C:\Alpha\watch1\specificconfig.txt", html);
                }
            }
        }

您无法从后台线程访问 ListView。您需要在 UI 线程上执行此操作。

有两个选项 - 首先,您可以将其切换为使用 Windows.Forms.Timer 每 30 秒触发一次。这将发生在 UI 线程上,这将完全避免这个问题,而是将处理转移到 UI 线程上。如果您的处理速度很慢,这可能会导致“挂起”。

或者,使用 Control.Invoke 将对 ListView 的调用封送回 UI 线程:

 listView2.Invoke(new Action( () => listView2.Items.Clear() ) );

无论如何,我会重新考虑使用BackgroundWorker。它不适用于定期发生的“定时事件”。如果不需要长时间处理,或者System.Timers.Timer(在后台线程上运行)如果处理需要一段时间。这是比永远不会终止的BackgroundWorker 更好的设计选项。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C# 线程问题 的相关文章