如何解决无法从另一个 Thread 访问 Thread 元素的问题
How to fix cannot access to a Thread elements from another Thread problem
我正在做一个 C# WinForms
项目。
我尝试在我的应用程序的一部分中使用 multi threading
:
部分代码(方法):
public void ShowData()
{
Thread t;
t = new Thread(() =>
{
using (GVentesEntities context = new GVentesEntities())
{
dataGridView1.DataSource = (from F in context.Facture.AsEnumerable() join C in context.Client.AsEnumerable() on F.CLT equals C.ID select new { ID = F.ID, F.Date, Client = $"{C.Nom} {C.Prenom}", Total = $"{(from df in context.Det_Fact.AsEnumerable() join cmd in context.Commande.AsEnumerable() on df.CMD equals cmd.ID where df.FACT == F.ID select cmd.QTE * cmd.PRU).Sum():00} MAD" }).OrderBy(x => int.Parse($"{x.ID.Substring(x.ID.IndexOf("-") + 1)}")).ToList();
}
});
Thread.Sleep(1000);
t.Start();
}
问题是当我在应用程序 运行 时尝试访问此方法时出现错误:
错误
System.InvalidOperationException: 'Cross-thread operation not valid: Control 'dataGridView1' accessed from a thread other than the thread it was created on.
'
请帮忙解决这个问题并使用线程执行我的方法?提前致谢。
您需要绑定回 UI 线程 - 例如
var values = (from F in context.Facture.AsEnumerable() join C in context.Client.AsEnumerable() on F.CLT equals C.ID select new { ID = F.ID, F.Date, Client = $"{C.Nom} {C.Prenom}", Total = $"{(from df in context.Det_Fact.AsEnumerable() join cmd in context.Commande.AsEnumerable() on df.CMD equals cmd.ID where df.FACT == F.ID select cmd.QTE * cmd.PRU).Sum():00} MAD" }).OrderBy(x => int.Parse($"{x.ID.Substring(x.ID.IndexOf("-") + 1)}")).ToList();
this.Invoke(new Action(() => this.dataGridView1.DataSource = values));
我正在做一个 C# WinForms
项目。
我尝试在我的应用程序的一部分中使用 multi threading
:
部分代码(方法):
public void ShowData()
{
Thread t;
t = new Thread(() =>
{
using (GVentesEntities context = new GVentesEntities())
{
dataGridView1.DataSource = (from F in context.Facture.AsEnumerable() join C in context.Client.AsEnumerable() on F.CLT equals C.ID select new { ID = F.ID, F.Date, Client = $"{C.Nom} {C.Prenom}", Total = $"{(from df in context.Det_Fact.AsEnumerable() join cmd in context.Commande.AsEnumerable() on df.CMD equals cmd.ID where df.FACT == F.ID select cmd.QTE * cmd.PRU).Sum():00} MAD" }).OrderBy(x => int.Parse($"{x.ID.Substring(x.ID.IndexOf("-") + 1)}")).ToList();
}
});
Thread.Sleep(1000);
t.Start();
}
问题是当我在应用程序 运行 时尝试访问此方法时出现错误:
错误
System.InvalidOperationException: 'Cross-thread operation not valid: Control 'dataGridView1' accessed from a thread other than the thread it was created on.
'
请帮忙解决这个问题并使用线程执行我的方法?提前致谢。
您需要绑定回 UI 线程 - 例如
var values = (from F in context.Facture.AsEnumerable() join C in context.Client.AsEnumerable() on F.CLT equals C.ID select new { ID = F.ID, F.Date, Client = $"{C.Nom} {C.Prenom}", Total = $"{(from df in context.Det_Fact.AsEnumerable() join cmd in context.Commande.AsEnumerable() on df.CMD equals cmd.ID where df.FACT == F.ID select cmd.QTE * cmd.PRU).Sum():00} MAD" }).OrderBy(x => int.Parse($"{x.ID.Substring(x.ID.IndexOf("-") + 1)}")).ToList();
this.Invoke(new Action(() => this.dataGridView1.DataSource = values));