datagridview-cross-threading-data-update ソースコード全文

DataGridView_Threading_Data_Update.sln

DataGridView_Threading_Data_Update.sln
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.14.37314.3 d17.14
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DataGridView_Threading_Data_Update", "DataGridView_Threading_Data_Update\DataGridView_Threading_Data_Update.csproj", "{72B436C3-3A7E-42B9-9B4E-21C12782047A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{72B436C3-3A7E-42B9-9B4E-21C12782047A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{72B436C3-3A7E-42B9-9B4E-21C12782047A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{72B436C3-3A7E-42B9-9B4E-21C12782047A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{72B436C3-3A7E-42B9-9B4E-21C12782047A}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {4F855958-2EA6-4428-8D22-115BC1A66FDD}
EndGlobalSection
EndGlobal

DataGridView_Threading_Data_Update/DataGridView_Threading_Data_Update.csproj

DataGridView_Threading_Data_Update.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net9.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
</Project>

DataGridView_Threading_Data_Update/DataGridView_Threading_Data_Update.csproj.user

DataGridView_Threading_Data_Update.csproj.user
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Compile Update="Form1.cs">
<SubType>Form</SubType>
</Compile>
</ItemGroup>
</Project>

DataGridView_Threading_Data_Update/Form1.cs

Form1.cs
using System.ComponentModel;
namespace DataGridView_Threading_Data_Update
{
public partial class Form1 : Form
{
private BindingList<MemberModel> _members = new();
public Form1()
{
InitializeComponent();
dataGridView1.DataSource = _members;
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
}
// �u�񓯊��Ńf�[�^�ǂݍ��݁v�{�^���̃N���b�N�C�x���g
private async void btnLoadAsync_Click(object sender, EventArgs e)
{
btnLoadAsync.Enabled = false;
lblStatus.Text = "�f�[�^�擾��...";
// 1. UI�X���b�h��� Progress �C���X�^���X���쐬�i�R�[���o�b�N���`�j
var progress = new Progress<MemberModel>(newMember =>
{
// ���̒������͎����I�ɁuUI�X���b�h�v�Ŏ��s����邽�߈��S�ł�
_members.Add(newMember);
});
// 2. �o�b�N�O���E���h�X���b�h�ŏd�����������s�iProgress��n���j
await Task.Run(() => FetchDataFromDatabaseAsync(progress));
lblStatus.Text = "�ǂݍ��݊���";
btnLoadAsync.Enabled = true;
}
// �[���I�Ƀf�[�^�x�[�X��API����f�[�^���擾����d�������i�ʃX���b�h�œ���j
private void FetchDataFromDatabaseAsync(IProgress<MemberModel> progress)
{
// �l�b�g���[�N�ʐM��d��SQL�N�G���̑���i2�b�ҋ@�j
Thread.Sleep(2000);
var data1 = new MemberModel("M001", "�R�c ���Y", "�J����");
progress.Report(data1); // UI�X���b�h�փf�[�^��͂���
Thread.Sleep(1000);
var data2 = new MemberModel("M002", "���� �Ԏq", "�c�ƕ�");
progress.Report(data2); // UI�X���b�h�փf�[�^��͂���
}
}
}

DataGridView_Threading_Data_Update/Form1.Designer.cs

Form1.Designer.cs
namespace DataGridView_Threading_Data_Update
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
tableLayoutPanel1 = new TableLayoutPanel();
dataGridView1 = new DataGridView();
btnLoadAsync = new Button();
lblStatus = new Label();
tableLayoutPanel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView1).BeginInit();
SuspendLayout();
//
// tableLayoutPanel1
//
tableLayoutPanel1.ColumnCount = 1;
tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100F));
tableLayoutPanel1.Controls.Add(dataGridView1, 0, 0);
tableLayoutPanel1.Controls.Add(btnLoadAsync, 0, 2);
tableLayoutPanel1.Controls.Add(lblStatus, 0, 1);
tableLayoutPanel1.Dock = DockStyle.Fill;
tableLayoutPanel1.Location = new Point(0, 0);
tableLayoutPanel1.Name = "tableLayoutPanel1";
tableLayoutPanel1.RowCount = 3;
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, 71.10198F));
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, 14.4485321F));
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, 14.4494829F));
tableLayoutPanel1.Size = new Size(800, 450);
tableLayoutPanel1.TabIndex = 0;
//
// dataGridView1
//
dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView1.Dock = DockStyle.Fill;
dataGridView1.Location = new Point(3, 3);
dataGridView1.Name = "dataGridView1";
dataGridView1.RowHeadersWidth = 62;
dataGridView1.Size = new Size(794, 313);
dataGridView1.TabIndex = 0;
//
// btnLoadAsync
//
btnLoadAsync.Dock = DockStyle.Fill;
btnLoadAsync.Location = new Point(3, 387);
btnLoadAsync.Name = "btnLoadAsync";
btnLoadAsync.Size = new Size(794, 60);
btnLoadAsync.TabIndex = 1;
btnLoadAsync.Text = "データ更新(非同期)";
btnLoadAsync.UseVisualStyleBackColor = true;
btnLoadAsync.Click += btnLoadAsync_Click;
//
// lblStatus
//
lblStatus.AutoSize = true;
lblStatus.Dock = DockStyle.Fill;
lblStatus.Location = new Point(3, 319);
lblStatus.Name = "lblStatus";
lblStatus.Size = new Size(794, 65);
lblStatus.TabIndex = 2;
//
// Form1
//
AutoScaleDimensions = new SizeF(10F, 25F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(tableLayoutPanel1);
Name = "Form1";
Text = "Form1";
tableLayoutPanel1.ResumeLayout(false);
tableLayoutPanel1.PerformLayout();
((System.ComponentModel.ISupportInitialize)dataGridView1).EndInit();
ResumeLayout(false);
}
#endregion
private TableLayoutPanel tableLayoutPanel1;
private DataGridView dataGridView1;
private Button btnLoadAsync;
private Label lblStatus;
}
}

DataGridView_Threading_Data_Update/Form1.resx

Form1.resx
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

DataGridView_Threading_Data_Update/MemberModel.cs

MemberModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace DataGridView_Threading_Data_Update
{
/// <summary>
/// メンバー情報を管理し、プロパティの変更を DataGridView などの UI に自動通知するデータモデルクラスです。
/// </summary>
public class MemberModel : INotifyPropertyChanged
{
// INotifyPropertyChanged インターフェースの変更通知イベント
public event PropertyChangedEventHandler? PropertyChanged;
private string _id = string.Empty;
private string _name = string.Empty;
private string _department = string.Empty;
/// <summary>
/// メンバーIDを取得または設定します。
/// </summary>
public string Id
{
get => _id;
set => SetProperty(ref _id, value);
}
/// <summary>
/// 氏名を取得または設定します。
/// </summary>
public string Name
{
get => _name;
set => SetProperty(ref _name, value);
}
/// <summary>
/// 所属部署を取得または設定します。
/// </summary>
public string Department
{
get => _department;
set => SetProperty(ref _department, value);
}
/// <summary>
/// MemberModel クラスの新しいインスタンスを初期化します。
/// </summary>
/// <param name="id">メンバーID</param>
/// <param name="name">氏名</param>
/// <param name="department">所属部署</param>
public MemberModel(string id, string name, string department)
{
_id = id;
_name = name;
_department = department;
}
/// <summary>
/// プロパティの値を安全に更新し、変更があった場合のみ PropertyChanged イベントを発行します。
/// </summary>
/// <typeparam name="T">プロパティの型</typeparam>
/// <param name="storage">バッキングフィールドへの参照</param>
/// <param name="value">変更後の新しい値</param>
/// <param name="propertyName">プロパティ名(呼び出し元のプロパティ名が自動で設定されます)</param>
protected void SetProperty<T>(ref T storage, T value, [CallerMemberName] string? propertyName = null)
{
// 変更前と変更後の値が同じであれば何もしない(無駄な描画処理をスキップ)
if (Equals(storage, value)) return;
// 値を更新
storage = value;
// UI(DataGridView)に対して変更を通知
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}

DataGridView_Threading_Data_Update/Program.cs

Program.cs
namespace DataGridView_Threading_Data_Update
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
}
}
}