我创建了两个dataGridViews和一个开始按钮,如图所示。
当我按下“开始”按钮时,使用代理MyDel创建了两个线程t1和t2。
实际上,我希望连续填充dataGridView1和dataGridView2。但只有dataGridView2会不断更新。 dataGridView2完成后,dataGridView1开始更新。
有人可以给我建议如何解决这个问题吗?
using System;
using System.Windows.Forms;
using System.Threading;
namespace MultiThreadedDataGridViewDemo
{
public partial class Form1 : Form
{
private delegate void MyDel();
int count=0;
int count_1 = 0;
public Form1()
{
InitializeComponent();
//Cells are created in dataGridView1 and dataGridView2
for (int p = 0; p < 37; p++)
{
dataGridView1.Columns.Add("", "");// dynamic cloumn adding
dataGridView1.Rows.Add();//dynamic row adding
dataGridView1.Columns[p].SortMode = DataGridViewColumnSortMode.NotSortable;//Disables the column header sorting
dataGridView1.Columns[p].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
dataGridView1.Columns[p].Width = 70;
dataGridView2.Columns.Add("", "");// dynamic cloumn adding
dataGridView2.Rows.Add();//dynamic row adding
dataGridView2.Columns[p].SortMode = DataGridViewColumnSortMode.NotSortable;//Disables the column header sorting
dataGridView2.Columns[p].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
dataGridView2.Columns[p].Width = 70;
}
}
//Method to populate dataGridView1
public void Method1()
{
while (count < 10000)
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
for (int k = 0; k < dataGridView1.Columns.Count; k++)
{
dataGridView1.Rows[i].Cells[k].Value = count;
}
}
count++;
}
}
//Method to populate dataGridView2
public void Method2()
{
while (count_1 < 10000)
{
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
for (int k = 0; k < dataGridView2.Columns.Count; k++)
{
dataGridView2.Rows[i].Cells[k].Value = count_1;
}
}
count_1++;
}
}
//Creates threads to populate dataGridView1 and dataGridView1
private void btn_Start_Click(object sender, EventArgs e)
{
MyDel del_1 = new MyDel(Method1);
Thread t1 = new Thread(new ThreadStart(del_1));
t1.Start();
MyDel del_2 = new MyDel(Method2);
Thread t2 = new Thread(new ThreadStart(del_2));
t2.Start();
}
}
}
答案 0 :(得分:0)
您应该使用BackgroundWorker
,并更新其ProgressChanged
- 事件中的用户界面,该事件用于访问UI
- 主题。使用ReportProgress
- 方法,您可以将int percentProgress
和object userState
发送到链接的ProgressChanged
- 方法。使用userState
- 对象,您可以传递一个完整的DataGridViewRows
列表,并将其ProgressChanged
- 方法添加到您的DataGridView
。