简体   繁体   English

委托具有多个签名的方法

[英]delegate a method with multiple signatures

How do I add a method with signature to a thread? 如何将带有签名的方法添加到线程?

I'm trying to add an item to TreeView GUI using a method testAdd(DirectoryEntry d, TreeNode t) 我正在尝试使用方法testAdd(DirectoryEntry d, TreeNode t)将项目添加到TreeView GUI

I did it as normal creation of a thread: 我将其作为线程的常规创建来完成:

Thread t1;
t1 = new Thread(new ThreadStart(testAdd(directory,rootNode));t1.Start();
t1=new Thread(delegate() {testAdd(directory, rootNode);})
t1.start();

I get error telling me to use invoke. 我收到告诉我使用invoke的错误消息。

How can this be solved? 如何解决呢?

The problem you're running into is that you can't access UI elements from a background thread in a WinForms application. 您遇到的问题是,您无法从WinForms应用程序中的后台线程访问UI元素。 There is nothing wrong with the signature you're using you're just doing an illegal operation on the UI element. 您使用的签名没有问题,您只是在UI元素上执行了非法操作。 The actual mutation of the UI element must occur on the UI / Main thread of the application. UI元素的实际变化必须在应用程序的UI /主线程上发生。 A new Thread instance guarantees this won't be true. 一个新的Thread实例保证这不会成立。

It's possible to do the work to calculate what you will add on a background thread and then use Invoke to get back to the UI thread. 可以完成计算将在后台线程上添加的内容,然后使用Invoke返回到UI线程的工作。 But the actual add must happen on the UI. 但是实际添加必须在UI上进行。

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

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