简体   繁体   English

如何在没有耦合的情况下从其他线程访问MainForm上的控件?

[英]How to access control on MainForm from other Thread without coupling?

I have few controls on my MainForm in Winforms application. 我在Winforms应用程序中的MainForm上几乎没有控件。 For example control that updates progress of each operation. 例如,用于更新每个操作的进度的控件。 These operations are classes which in run in different Thread. 这些操作是在不同的Thread中运行的类。

How can i properly update those controls ? 我该如何正确更新这些控件?

the best way is to do that by events. 最好的方法是通过活动来做到这一点。 the easier way is to change them directly. 更简单的方法是直接更改它们。

ensure that they are public and you overgive them to the class and then you can change it 确保他们是公开的,并且你将他们原谅他们上课,然后你可以改变它

Invoke(new MethodInvoker(delegate { frmMain.label1.Text = "bla"; }));

in your main form you can add a function like this one 在您的主窗体中,您可以添加类似这样的功能

private delegate void doSomethingWithTheControlsDelegate(object obj);

public void doSomethingWithTheControls(object obj) {
 if (this.InvokeRequired) {
   this.BeginInvoke(new doSomethingWithTheControlsDelegate(this.doSomethingWithTheControls), obj);
 } else {
   // do something
 }
}

I would suggest using a model class which would contain the data which is displayed to the user. 我建议使用一个模型类,它将包含显示给用户的数据。 Databind your UI controls to the properties of the model, and update the model values from the worker threads (using appropriate invokations to ensure the update occurs on the UI thread so that you don't get the cross thread exception) 将UI控件数据绑定到模型的属性,并从工作线程更新模型值(使用适当的调用以确保在UI线程上进行更新,以便您不会获得跨线程异常)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM