c# - "Cross-thread operation not valid: Control 'form1' accessed from a thread other than the thread it was created on."
问题描述
I have a winforms project which has formA
and formB
. When formA
loads, it calls class Calculation
to do some logic and opens formB
to display something. formA
has a button to close formB
. When I click the button to close formB
, it give me an error:
"Cross-thread operation not valid: Control 'formB' accessed from a thread other than the thread it was created on."
List<Form> forms = new List<Form>();
formA_Load()
{
DemoObject calfrmA = new DemoObject();
calfrmA.getData();
}
public class DemoObject
{
public void getData()
{
formB frmB = new frmB();
frmB.Name = "frmB";
forms.Add(frmB);
frmB.Show();
}
}
formA
button click
public void button1_click()
{
foreach(Form frm in forms)
{
if(frm.Name == "frmB")
{
frm.Close();
}
}
}
the frm.Close()
gives an error. How I can fix the issue? Please guide me. Thanks
Edited code: I have tried but still the same. DemoObject
is a class.
formA_Load()
{
foreach (DemoObject tobject in objectList.Values) {
Thread thread = new Thread(delegate ()
{
this.Invoke(new MethodInvoker(delegate
{
tobject.getData();
}));
});
thread.Start();
}
}
解决方案
推荐阅读
- reactjs - 如何在 React 中为每个屏幕尺寸设置尺寸?
- matlab - 使用 Matlab 基于密度函数生成具有不等步长的网格
- llvm - 在 LLVM 中创建一个包含指向自身的指针的结构
- linux - 签署虚拟盒模块(vboxdrv、vboxnetflt、vboxnetadp、vboxpci)Centos 8
- laravel - 导入CSV文件,删除空行并立即导出而不将其存储到数据库中 - laravel excel
- twitter-bootstrap - Bootstrap .container 和 .container-sm 之间的区别
- javascript - 我需要在 javascript / jQuery 中获取嵌套对象中的值列表
- android - 从android中的Html标签重定向到链接
- python - Python Tkinter - 形状调整
- ng-bootstrap - 如何使用 Ng-Bootstrap 6 在 Angular 9 中正确实现 Tooltip