且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从静态方法更新Windows窗体控件数据

更新时间:2023-12-06 11:45:22

唯一的方法克服这个问题的做法是:不要使用静态方法。



你可以通过创建一个静态Form变量并将其加载到表单实例来绕过它,但是它只是:一个小屋。一旦你有两个表格实例,它就会崩溃。



那么看看为什么你需要一个静态方法,并检查你确实需要一个静态处理程序:我怀疑你是否在实践中。请记住,在UI线程上没有执行DataReceived事件处理程序 - 您需要调用要访问的任何控件以避免交叉线程问题。
The only way in practice to overcome this is: don't use a static method.

You can bodge round it by creating a static Form variable and loading it with your form instance, but it is just that: a bodge. And as soon as you have two instances of the form it all falls apart.

So look at why you need a static method, and check that you really do need a static handler: I doubt if you do in practice. And please, do remember that the DataReceived event handler is not executed on the UI thread - you will need to Invoke any controls you want to access to avoid cross thread problems.