C#实现计算数据和刷新ListView列表并发执行

下面是一个示例代码,演示如何在C#中实现计算列表的数据和刷新ListView控件的数据的并发执行:

cs 复制代码
using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows.Forms;

class Program
{
    static List<int> dataList = new List<int>();
    static ListView listView = new ListView() { View = View.Details };

    static void Main()
    {
        // 添加列头
        listView.Columns.Add("Data");

        // 启动两个线程并发执行计算和刷新列表的操作
        Thread computeThread = new Thread(() => ComputeData(10, 20));
        computeThread.Start();

        Thread refreshThread = new Thread(() => RefreshListView());
        refreshThread.Start();

        Application.Run(new Form() { Controls = { listView } });
    }

    static void ComputeData(int a, int b)
    {
        int sum = a + b;
        Console.WriteLine($"Sum of {a} and {b} is {sum}");

        lock (dataList)
        {
            dataList.Add(sum);
        }
    }

    static void RefreshListView()
    {
        while (true)
        {
            Thread.Sleep(1000);

            lock (dataList)
            {
                listView.Items.Clear();
                foreach (var data in dataList)
                {
                    listView.Items.Add(new ListViewItem(data.ToString()));
                }
            }
        }
    }
}

在这个示例中,我们创建了一个ListView控件用来显示数据。然后启动了两个线程,一个用来计算数据并添加到列表中,另一个用来刷新ListView控件的数据。在计算数据时我们使用了lock保护dataList,确保数据的线程安全性。在刷新ListView时也同样使用了lock来避免多线程访问导致的并发问题。

请注意,这个示例中使用了Thread.Sleep(1000);来模拟每隔一秒刷新一次ListView的操作。在实际应用中,您可以根据具体需求来调整刷新频率。此外,为了在Windows窗体应用程序中运行,我们使用了Application.Run方法启动了主窗体。

相关推荐
lly20240642 分钟前
jQuery Mobile 表格
开发语言
惊讶的猫1 小时前
探究StringBuilder和StringBuffer的线程安全问题
java·开发语言
m0_748233171 小时前
30秒掌握C++核心精髓
开发语言·c++
Fleshy数模2 小时前
从数据获取到突破限制:Python爬虫进阶实战全攻略
java·开发语言
Duang007_2 小时前
【LeetCodeHot100 超详细Agent启发版本】字母异位词分组 (Group Anagrams)
开发语言·javascript·人工智能·python
froginwe112 小时前
Redis 管道技术
开发语言
u0109272712 小时前
C++中的RAII技术深入
开发语言·c++·算法
superman超哥3 小时前
Serde 性能优化的终极武器
开发语言·rust·编程语言·rust serde·serde性能优化·rust开发工具
一个响当当的名号3 小时前
lectrue9 索引并发控制
java·开发语言·数据库
2401_832131953 小时前
模板错误消息优化
开发语言·c++·算法