WPF Datagrid loaded 79M items in mvvm , Microsoft.Extensions.DependencyInjection

news/2025/9/24 21:10:50/文章来源:https://www.cnblogs.com/Fred1987/p/19109985

 

Install-Package Microsoft.Extensions.DependencyInjection;

 

 

image

 

        public async Task InitBooksCollection(){stopwatch.Start();BooksCollection = new ObservableCollection<Book>();List<Book> booksList = new List<Book>();await Task.Run(async () =>{for (int i = 1; i < 100000001; i++){booksList.Add(new Book(){Id = idService.GetID(),Name = nameService.GetName(),ISBN = isbnService.GetISBN(),Author = $"Author_{i}",Title = $"Title_{i}",Topic = $"Topic_{i}"});if (i < 1001 && i % 100 == 0){var tempList = booksList.ToList();booksList.Clear();await PopulateBooksCollection(tempList);}else if (i > 1000 && i % 1000000 == 0){var tempList = booksList.ToList();booksList.Clear();await PopulateBooksCollection(tempList);}}if (booksList.Any()){var tempList = booksList.ToList();booksList.Clear();await PopulateBooksCollection(tempList);}});}private async Task PopulateBooksCollection(List<Book> booksList){await Application.Current.Dispatcher.InvokeAsync(() =>{foreach (var bk in booksList){BooksCollection.Add(bk);}StatusMsg = $"MainWindow,now is {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}," +$"loaded {BooksCollection.Count} items,{GetMemory()},{GetTimeCost()}";}, System.Windows.Threading.DispatcherPriority.Background);System.Diagnostics.Debug.WriteLine(StatusMsg);}private string GetMemory(){double memory = Process.GetCurrentProcess().PrivateMemorySize64;return $"Memory:{memory.ToString("#,##0.00")}";}private string GetTimeCost(){return $"Time cost:{stopwatch.Elapsed.TotalSeconds.ToString("#,##0.00")} seconds";}

 

 

 

 

 

 

 

 

 

 

image

 

 

 

 

 

 

 

image

 

 

//App.xaml
<Application x:Class="WpfApp5.App"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:local="clr-namespace:WpfApp5"><Application.Resources></Application.Resources>
</Application>//App.xaml.cs
using Microsoft.Extensions.DependencyInjection;
using System.Configuration;
using System.Data;
using System.Windows;
using WpfApp5.Services;namespace WpfApp5
{/// <summary>/// Interaction logic for App.xaml/// </summary>public partial class App : Application{ServiceProvider serviceProvider;protected override void OnStartup(StartupEventArgs e){base.OnStartup(e);var services = new ServiceCollection();ConfigureServices(services);serviceProvider = services.BuildServiceProvider();var mainWin = serviceProvider.GetRequiredService<MainWindow>();mainWin?.Show();}private void ConfigureServices(ServiceCollection services){services.AddSingleton<IISBNService, ISBNService>();services.AddSingleton<INameService, NameService>();services.AddSingleton<IIDService, IDService>();services.AddSingleton<MainWindow>();services.AddSingleton<MainVM>();}}}//MainWindow.xaml
<Window x:Class="WpfApp5.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"WindowState="Maximized"xmlns:local="clr-namespace:WpfApp5"mc:Ignorable="d"Title="{Binding StatusMsg}"Height="450" Width="800"><Grid><DataGrid ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"VirtualizingPanel.IsVirtualizing="True"VirtualizingPanel.VirtualizationMode="Recycling"VirtualizingPanel.ScrollUnit="Pixel"VirtualizingPanel.CacheLengthUnit="Pixel"VirtualizingPanel.CacheLength="1,2"                    ScrollViewer.IsDeferredScrollingEnabled="True"ScrollViewer.CanContentScroll="True"EnableColumnVirtualization="True"EnableRowVirtualization="True"AutoGenerateColumns="False"><DataGrid.Resources><Style TargetType="DataGridCell"><Setter Property="FontSize" Value="30"/><Setter Property="Width" Value="Auto"/><Style.Triggers><Trigger Property="FontSize" Value="50"/><Trigger Property="Foreground" Value="Red"/></Style.Triggers></Style></DataGrid.Resources><DataGrid.Columns><DataGridTextColumn Binding="{Binding Id}"/><DataGridTextColumn Binding="{Binding Name}"/><DataGridTextColumn Binding="{Binding Author}"/><DataGridTextColumn Binding="{Binding Title}"/><DataGridTextColumn Binding="{Binding Topic}"/><DataGridTextColumn Binding="{Binding ISBN}"/><!--<DataGridTemplateColumn><DataGridTemplateColumn.CellTemplate><DataTemplate><Grid><Grid.Resources><Style TargetType="TextBlock"><Setter Property="FontSize" Value="30"/><Style.Triggers><Trigger Property="IsMouseOver" Value="True"><Setter Property="FontSize" Value="50"/><Setter Property="Foreground" Value="Red"/></Trigger></Style.Triggers></Style><Style TargetType="ColumnDefinition"><Setter Property="Width" Value="Auto"/></Style></Grid.Resources><Grid.ColumnDefinitions><ColumnDefinition/><ColumnDefinition/><ColumnDefinition/><ColumnDefinition/><ColumnDefinition/><ColumnDefinition/></Grid.ColumnDefinitions><TextBlock Text="{Binding Id}" Grid.Column="0"/><TextBlock Text="{Binding Name}" Grid.Column="1"/><TextBlock Text="{Binding Author}" Grid.Column="2"/><TextBlock Text="{Binding Title}" Grid.Column="3"/><TextBlock Text="{Binding Topic}" Grid.Column="4"/><TextBlock Text="{Binding ISBN}" Grid.Column="5"/></Grid></DataTemplate></DataGridTemplateColumn.CellTemplate></DataGridTemplateColumn>--></DataGrid.Columns></DataGrid></Grid>
</Window>//MainWindow.xaml.cs
using CommunityToolkit.Mvvm.ComponentModel;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WpfApp5.Services;namespace WpfApp5
{/// <summary>/// Interaction logic for MainWindow.xaml/// </summary>public partial class MainWindow : Window{public MainWindow(){InitializeComponent();}public MainWindow(MainVM vm){InitializeComponent();RenderOptions.ProcessRenderMode=System.Windows.Interop.RenderMode.Default;this.DataContext = vm;Loaded += async (s, e) =>{await vm.InitBooksCollection();};}}public class MainVM : INotifyPropertyChanged{private IIDService idService;private INameService nameService;private IISBNService isbnService;private Stopwatch stopwatch;public MainVM(IIDService idServiceValue, INameService nameServiceValue, IISBNService isbnServiceValue){stopwatch = new Stopwatch();StatusMsg = $"MainWindow,now is {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")},{GetMemory()},{GetTimeCost()}";idService = idServiceValue;nameService = nameServiceValue;isbnService = isbnServiceValue;}public async Task InitBooksCollection(){stopwatch.Start();BooksCollection = new ObservableCollection<Book>();List<Book> booksList = new List<Book>();await Task.Run(async () =>{for (int i = 1; i < 100000001; i++){booksList.Add(new Book(){Id = idService.GetID(),Name = nameService.GetName(),ISBN = isbnService.GetISBN(),Author = $"Author_{i}",Title = $"Title_{i}",Topic = $"Topic_{i}"});if (i < 1001 && i % 100 == 0){var tempList = booksList.ToList();booksList.Clear();await PopulateBooksCollection(tempList);}else if (i > 1000 && i % 1000000 == 0){var tempList = booksList.ToList();booksList.Clear();await PopulateBooksCollection(tempList);}}if (booksList.Any()){var tempList = booksList.ToList();booksList.Clear();await PopulateBooksCollection(tempList);}});}private async Task PopulateBooksCollection(List<Book> booksList){await Application.Current.Dispatcher.InvokeAsync(() =>{foreach (var bk in booksList){BooksCollection.Add(bk);}StatusMsg = $"MainWindow,now is {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}," +$"loaded {BooksCollection.Count} items,{GetMemory()},{GetTimeCost()}";}, System.Windows.Threading.DispatcherPriority.Background);System.Diagnostics.Debug.WriteLine(StatusMsg);}private string GetMemory(){double memory = Process.GetCurrentProcess().PrivateMemorySize64;return $"Memory:{memory.ToString("#,##0.00")}";}private string GetTimeCost(){return $"Time cost:{stopwatch.Elapsed.TotalSeconds.ToString("#,##0.00")} seconds";}public event PropertyChangedEventHandler? PropertyChanged;private void OnPropertyChanged([CallerMemberName] string propertyName = ""){var handler = PropertyChanged;if (handler != null){handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));}}private ObservableCollection<Book> booksCollection;public ObservableCollection<Book> BooksCollection{get{return booksCollection;}set{if (value != booksCollection){booksCollection = value;OnPropertyChanged();}}}private string statusMsg;public string StatusMsg{get{return statusMsg;}set{if (value != statusMsg){statusMsg = value;OnPropertyChanged();}}}}public class DelCommand : ICommand{private Action<object?> execute;private Predicate<object?> canExecute;public DelCommand(Action<object?> executeValue, Predicate<object?> canExecuteValue){execute = executeValue;canExecute = canExecuteValue;}public event EventHandler? CanExecuteChanged{add{CommandManager.RequerySuggested += value;}remove{CommandManager.RequerySuggested -= value;}}public bool CanExecute(object? parameter){return canExecute == null ? true : canExecute(parameter);}public void Execute(object? parameter){execute(parameter);}}public class Book{public int Id { get; set; }public string Name { get; set; }public string Author { get; set; }public string Title { get; set; }public string Topic { get; set; }public string ISBN { get; set; }}
}//IDService.cs
using System;
using System.Collections.Generic;
using System.Text;namespace WpfApp5.Services
{public interface IIDService{int GetID();}public class IDService : IIDService{int id = 0;public int GetID(){return Interlocked.Increment(ref id);}}
}//ISBNService.cs
using System;
using System.Collections.Generic;
using System.Text;namespace WpfApp5.Services
{public interface IISBNService{string GetISBN();}public class ISBNService : IISBNService{int idx = 0;public string GetISBN(){return $"ISBN_{Interlocked.Increment(ref idx)}_{Guid.NewGuid():N}";}}
}//NameService.cs
using System;
using System.Collections.Generic;
using System.Text;namespace WpfApp5.Services
{public interface INameService{string GetName();}public class NameService : INameService{int idx = 0;public string GetName(){return $"Name_{Interlocked.Increment(ref idx)}";}}
}

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/916245.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

实用指南:python+django/flask的宠物救助及领养系统javaweb

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …

Linux 系统中的 /dev/disk/by-id/目录作用详解

Linux 系统中的 /dev/disk/by-id/目录作用详解Linux 系统中的 /dev/disk/by-id/目录是一个非常重要的组成部分,它能帮助咱们更稳定、更可靠地管理磁盘设备。下面我来为你详细解释它的作用和用法。 📁 一、/dev/disk…

万江专业网站快速排名个人免费网站注册

本研究的主要目的是基于Python aiortc api实现抓取本地设备媒体流&#xff08;摄像机、麦克风&#xff09;并与Web端实现P2P通话。本文章仅仅描述实现思路&#xff0c;索要源码请私信我。 1 demo-server解耦 1.1 原始代码解析 1.1.1 http服务器端 import argparse import …

glTF/glb:您需要知道的一切,怎么免费获取下载

有一种新的丰富 3D 模型格式,称为 glTF,并且一直在崛起。本文将告诉您有关 glTF 的所有信息,包括它是什么、为什么开发它以及谁在使用它。glb下载官网免费获取模型什么是glTF? GL 传输格式(简称 glTF)是一种开源…

成品网站短视频源码搭建网站建设培训 苏州

首次连接 打开装有 AirPods 的充电盒&#xff0c;并将它放在 iPhone 旁边。此时你的 iPhone 上将出现设置动画。轻点「连接」&#xff0c;然后轻点「完成」。 就这么简单&#xff0c;而且会自动设置&#xff0c;实现与已使用同一 Apple ID 登录 iCloud 的任一支持设备搭配使用…

3.HTTP/HTTPS:报文格式、技巧、状态码、缓存、SSLTLS握手

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …

keepalived服务器

keepalived服务器keepalived高可用原理:搭建主、备服务器一样配置,在keepalived中配置相同的vip;主服务器发送“心跳消息”给备服务器,主服务器宕机,“心跳消息”停止发送,备服务器会让vip生效,产生“IP漂移”,…

外部 Tomcat 部署详细 - 实践

外部 Tomcat 部署详细 - 实践pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco"…

20231326《密码系统设计》第三周预习报告

20231326《密码系统设计》第三周预习报告20231326《密码系统设计》第三周预习报告 目录20231326《密码系统设计》第三周预习报告学习内容《Head First C 嗨翻 C 语言》第4章《Windows C/C++加密解密实战》第4章AI 对学…

吉林网站开发公司网站首页设计html代码

作者| Rohan Wadiwala、Mangesh More翻译 | 天道酬勤&#xff0c;编辑 | Carol出品| CSDN云计算&#xff08;ID&#xff1a;CSDNcloud&#xff09;在分析的世界中&#xff0c;网站的每次点击都是数据分析的候选对象&#xff0c;显然&#xff0c;这会涉及大量的数据生成。对于海…

做普工招聘网站上海汽车设计公司名单

静态长效代理IP和动态短效代理IP是两种常见的代理IP类型&#xff0c;它们在用途和适用场景上存在一定的差异。了解它们的特性以及使用场景有助于我们更好地利用代理IP&#xff0c;提高网络访问的效率和安全性。 一、静态长效代理IP 1. 用途 静态长效代理IP是指长期保持稳定的代…

深圳做网站专业的公司如何做英文网站推广

来源&#xff1a;数码之家文 | 禅哥这台机器在本人的eBay收藏夹里呆了很久&#xff0c;某日无意间扫了一眼收藏夹&#xff0c;突然发现卖家大降价&#xff0c;只要15刀&#xff0c;还有best offer选项。15刀你买不了吃亏&#xff0c;15刀你买不了上当。事不宜迟果断下手。根据非…

天津星创网站建设有限公司微信小商店分销系统

977. 有序数组的平方y 思路&#xff0c;原数组是有序的&#xff0c;但是因为负数平方后可能变无序了&#xff0c;因此利用双指针遍历原数组&#xff0c;比较 nums[left]*nums[left]和nums[right]*nums[right]谁更大&#xff0c;然后对新数组赋值 class Solution {public int…

FortiGate连接中国联通SDWAN

最近上线SAP,需要使用公司飞塔防火墙连接中国联通SDWAN,记录下过程吧。 飞塔防火墙型号F200E,有2条互联网带宽,需要分别与联通建立IPSEC+BGP连接。 联通会提供2个IPSEC配置信息+2个BGP配置信息 1,在飞塔完成2条IP…

第五章 运算符、表达式和语句

本章将介绍以下内容: 1、关键字——while、typedef; 2、运算符——=、-、*、/、%、++、--; 3、C语言的各种运算符,包括用于普通数学运算的运算符; 4、运算符优先级以及语句、表达式的含义; 5、while循环; 6、复…

wordpress 淘宝客网站模板平面设计与网页设计

Hi1102A和Hi1105V500都是属于海思旗下的两款WIFIBTGNSSFM四功能一体(江湖俗称四合一)高性能方案&#xff0c;应该可以推出&#xff0c;这个原本是在手机方案集成使用的&#xff0c;本身海思有视频安防主控HI315X系列平台&#xff0c;如果搭配上自己的无线phy芯片&#xff0c;一…

广州网站建设 易企建站公司网站开发和运营合同分开签么

以前的大部分程序都是操作Chrome&#xff0c;很少有操作Edge&#xff0c;现在以Edge为例。 Selenium本身是无法直接控制浏览器的&#xff0c;不同的浏览器需要不同的驱动程序&#xff0c;Google Chrome需要安装ChromeDriver、Edge需要安装Microsoft Edge WebDriver&#xff0c…

【Golang】素材设计模式

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …

学习问题日记-2

在开发过程中遇到了一个问题,报错描述如下:java: 无法将类 com.chools.demo.entity.Address中的构造器 Address应用到给定类型; 需要: 没有参数 找到: java.lang.String,java.lang.String,java.lang.String …

樟树网站制作wordpress在线音乐

电脑的设备驱动程序&#xff1a;驱动程序一般指的是设备驱动程序(DeviceDriver)&#xff0c;是一种可以使计算机和设备通信的特殊程序。相当于硬件的接口&#xff0c;操作系统只有通过这个接口&#xff0c;才能控制硬件设备的工作&#xff0c;如某设备的驱动程序未能正确安装&a…