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方法启动了主窗体。

相关推荐
chenyuhao20241 分钟前
Linux系统编程:线程概念与控制
linux·服务器·开发语言·c++·后端
冷雨夜中漫步3 分钟前
Java类加载机制——双亲委派与自定义类加载器
java·开发语言·python
weibkreuz11 分钟前
模块与组件、模块化与组件化的理解@3
开发语言·前端·javascript
乾元30 分钟前
用 AI 做联动:当应用层出现问题,网络如何被“自动拉入决策回路”
运维·开发语言·网络·人工智能·ci/cd·自动化
尘心cx33 分钟前
前端-APIs-day3
开发语言·前端·javascript
gfdhy34 分钟前
【c++】素数详解:概念、定义及高效实现(判断方法 + 筛法)
开发语言·c++·算法·数学建模·ai编程
Dargon28835 分钟前
MATLAB的Simulink的While子系统(动作子系统)
开发语言·matlab·simulink·mbd软件开发
Dargon28835 分钟前
MATLAB的Simulink的可变子系统(选择子系统)
开发语言·matlab
崇山峻岭之间35 分钟前
Matlab学习记录08
开发语言·学习·matlab
吴佳浩 Alben41 分钟前
Python入门指南(五) - 为什么选择 FastAPI?
开发语言·python·fastapi