0
如何使用线程更改Gridview中的某些单元格?我有一个来自数据库的查询,它用了很多时间来查询。所以它非常慢,我想使用线程更快加载数据。此外,线程完成后,它的工作可以更改网格视图中的数据?如何使用线程更改Gridview中的某些单元格?
如何使用线程更改Gridview中的某些单元格?我有一个来自数据库的查询,它用了很多时间来查询。所以它非常慢,我想使用线程更快加载数据。此外,线程完成后,它的工作可以更改网格视图中的数据?如何使用线程更改Gridview中的某些单元格?
using System.Threading;
using System.Threading.Tasks;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
dataGridView1.DataSource = new List<Test>() { new Test { Name = "Original Value" } };
}
// Start the a new Task to avoid blocking the UI Thread
private void button1_Click(object sender, EventArgs e)
{
Task.Factory.StartNew(this.UpdateGridView);
}
// Blocks the UI
private void button2_Click(object sender, EventArgs e)
{
UpdateGridView();
}
private void UpdateGridView()
{
//Simulate long running operation
Thread.Sleep(3000);
Action del =() =>
{
dataGridView1.Rows[0].Cells[0].Value = "Updated value";
};
// If the caller is on a different thread than the one the control was created on
// http://msdn.microsoft.com/en-us/library/system.windows.forms.control.invokerequired%28v=vs.110%29.aspx
if (dataGridView1.InvokeRequired)
{
dataGridView1.Invoke(del);
}
else
{
del();
}
}
}
问题是如何实现线程或如何在填充网格时避免跨线程异常? – DaveShaw 2011-02-05 23:30:51
请更具体。你有什么不明白? – 2011-02-05 23:43:25