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

相关推荐
程序大视界23 分钟前
【Python系列课程】Python入门教程
开发语言·人工智能·python
morning_judger30 分钟前
Agent系列(二)-记忆系统的设计
开发语言·python·机器学习
方也_arkling31 分钟前
【Java-Day02】语法篇:变量/数据类型/标识符/运算符/类型转换
java·开发语言
RSTJ_162533 分钟前
PYTHON+AI LLM DAY SIXTY-ONE
开发语言·python
zfoo-framework35 分钟前
理解kotlin limitedParallelism(1)与Actor模型
android·开发语言·kotlin
.千余1 小时前
【C++】C++类与对象3:const成员函数与取地址运算符重载,权限管理的艺术
开发语言·c++
影寂ldy1 小时前
C# 类和对象
开发语言·c#
丷丩1 小时前
MapLibre GL JS第25课:添加栅格瓦片源
开发语言·javascript·gis·mapbox·maplibre gl js
朔北之忘 Clancy1 小时前
2026 年 3 月青少年软编等考 C 语言二级真题解析
c语言·开发语言·c++·学习·青少年编程·题解·考级
Old Uncle Tom2 小时前
Harness Engineering 综述
java·开发语言·数据库