在C#中将实例方法传递给线程 [英] Passing Instance Method to Thread in C#

查看:71
本文介绍了在C#中将实例方法传递给线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想同时从另一个类运行两个方法。显然,下面的代码不起作用。我怎么能这样做?



节点node =  new 节点(); 
EHNode ehnode = new EHNode();

线程normalNode = new 线程(node.RunNode());
线程ehNode = 线程(ehnode.RunNode());

normalNode.Start();
ehNode.Start();

解决方案

是的,这个问题很有意思。我解决这个问题的方法是使用线程包装器。这个想法是:将this传递给线程,该线程是对包装器的引用。这将打开线程代码的包装器的所有实例成员(不仅是实例方法)。 (如果你共享任何一个,不要忘记使用线程同步,但线程包装器也有助于很好地封装同步原语。)



更多细节,请查看我过去的答案,并附上代码示例:

http://www.codeproject.com/Answers/155852/How-to-pass-ref-parameter-to-the-thread#answer2 [ ^ ],

http:// www.codeproject.com/Answers/223412/change-paramters-of-thread-producer-after-it-start#answer1 [ ^ ],

http://www.codeproject.com/Answers/485734/MultiThreadingplusinplusC-23#answer4 [ ^ ]。



你明白了吗?



-SA


< blockquote>你有 Node EHNode 的来源,是吗?然后你可以添加一个方法 StartRunNode(),它用 RunNode()创建一个新线程,启动它,然后返回到来电者。


I want to run two methods from another class simultaneously. Obviously, the code below will not work. How can I do something like this?

Node node = new Node();
EHNode ehnode = new EHNode();

Thread normalNode = new Thread(node.RunNode());
Thread ehNode = new Thread(ehnode.RunNode());

normalNode.Start();
ehNode.Start();

解决方案

Yes, the question is interesting. My method of solving such problem is using a thread wrapper. The idea is: pass "this" to the thread, which is the reference to the wrapper. This will open all the instance members (not only instance methods) of the wrapper to the thread code. (Don''t forget to use thread synchronization if you share any of them, but a thread wrapper also helps to encapsulate the synchronization primitives nicely.)

For further detail, please see my past answers, complete with code samples:
http://www.codeproject.com/Answers/155852/How-to-pass-ref-parameter-to-the-thread#answer2[^],
http://www.codeproject.com/Answers/223412/change-paramters-of-thread-producer-after-it-start#answer1[^],
http://www.codeproject.com/Answers/485734/MultiThreadingplusinplusC-23#answer4[^].

Did you get the idea?

—SA


Do you have the sources for Node and EHNode, resp.? Then you could add a method StartRunNode() which creates a new thread with RunNode(), starts it, and returns to the caller.


这篇关于在C#中将实例方法传递给线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆