下面是一個示例代碼,演示如何在C#中實現計算列表的數據和刷新ListView
控件的數據的并發執行:
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
方法啟動了主窗體。