因此,对于管理软件,我有一个需要实时更新的数据网格视图。我尝试在单独的线程上更新控件,但它会引发异常:
Cross-thread operation not valid: Control 'dataGridView1' accessed from a thread other than the thread it was created on.
以下是代码:
public void atualiza()
{
for (int i = 0; ; i++)
{
i--;
tabela();
System.Threading.Thread.Sleep(90000);
}
}
private void mainUser_Load(object sender, EventArgs e)
{
atualizaTabela t = new atualizaTabela(atualiza);
t.BeginInvoke(null, null);
}
" Tabela"是实际更新数据网格视图的方法:
public void tabela()
{
string comando = "SELECT * FROM Job";
OracleDataAdapter da;
OracleCommand comm;
DataSet ds;
OracleConnection Conn = new OracleConnection(dbstring);
comm = new OracleCommand(comando, Conn);
da = new OracleDataAdapter(comm);
ds = new DataSet();
da.Fill(ds, "Job");
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Job";
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
dataGridView1.Columns[0].HeaderText = "Id";
dataGridView1.Columns[1].HeaderText = "Produto";
dataGridView1.Columns[2].HeaderText = "Cliente";
dataGridView1.Columns[3].HeaderText = "Data de Pedido";
dataGridView1.Columns[4].HeaderText = "Previsão de Entrega";
dataGridView1.Columns[5].HeaderText = "Preço";
dataGridView1.Columns[6].HeaderText = "Tamanho";
dataGridView1.Columns[7].HeaderText = "Quantidade";
dataGridView1.Columns[8].HeaderText = "Comentário";
}
" Atualizatabela"是代表。当我尝试将datagridview绑定到数据源时抛出异常:(dataGridView1.DataSource = ds)
答案 0 :(得分:2)
如异常所述,您无法从非UI线程访问UI元素。
我建议使用BackgroundWorker
。你可以read all about it here。
以下是您需要完成的基本概要:
WinForms
,因此请将BackgroundWorker
放到Form
上。WorkerReportsProgress
属性设置为True
。DoWork
和ProgressChanged
个活动。DoWork
事件中的数据库中获取数据,该事件位于单独的线程中。ProgressChanged
ReportProgress
活动
ProgressChanged
事件内的数据更新网格,然后您将无法获得"跨线程操作"异常。答案 1 :(得分:0)
UI控件通常只能在创建它们的线程上进行操作。要避免此错误,请使用名为 Invoke()的方法,该方法可以从单独的线程调用,以便在控件的创建线程上运行代码。因此,在tabela()函数检索到ds中的数据后,您可以执行以下操作:
dataGridView1.Invoke(new Action(() =>
{
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Job";
...
}));
};