将对象传递给线程失败 - C#
我一直在尝试将一个对象传递给我的主线程进程,但它似乎不会按照我想象的方式工作。
首先,我创建线程:
Thread thrUDP;
然后创建将用于存储所需数据的对象:
UDPData udpData;
现在我使用正确的数据初始化对象,设置新线程并使用传递到 Start() 方法的对象启动
udpData = new UDPData("224.5.6.7", "5000", "0", "2");
thrUDP = new Thread(new ParameterizedThreadStart(SendStatus));
thrUDP.Start(udpData);
它 :是我希望开始的方法:
private void SendStatus(UDPData data)
{
}
我记得不久前使用过线程,我确信它们传递数据并不那么困难,我这样做的方式是否错误,或者我只是错过了一段代码?
谢谢!
I've been trying to pass an object to my main thread process but it seems it will not work in the way I thought it would.
First I create the Thread:
Thread thrUDP;
Then I create the object I will use to store the data I need:
UDPData udpData;
Now I Initialize the object withthe correct data, Set up the new thread and start it with the object passed into the Start() method:
udpData = new UDPData("224.5.6.7", "5000", "0", "2");
thrUDP = new Thread(new ParameterizedThreadStart(SendStatus));
thrUDP.Start(udpData);
This is the method I wish to start:
private void SendStatus(UDPData data)
{
}
I remember using Threads a while back and I'm sure they weren't so difficult to pass data to, am I doing this the wrong way or am I just missing a piece of code?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
ParameterizedThreadStart
委托是声明为:显然,此委托与您的方法的签名不兼容,并且没有直接的方法可以让
System.Threading.Thread
与任意委托类型一起使用。您的选择之一是为该方法使用兼容的签名,并进行适当的转换:
另一个选择是将问题转嫁给 C# 编译器,创建一个闭包。例如:
请注意,这使用了 ThreadStart 委托。此外,您在随后修改 udpData 本地数据时应小心,因为它已被捕获。
或者,如果您不介意使用线程池而不是生成自己的线程,则可以使用异步委托。例如:
The
ParameterizedThreadStart
delegate is declared as:Clearly, this delegate isn't compatible with your method's signature, and there isn't a direct way to get a
System.Threading.Thread
to work with an arbitrary delegate-type.One of your options would be to use a compatible signature for the method, and cast as appropriate:
The other option would be to punt the problem to the C# compiler, creating a closure. For example:
Do note that this uses the
ThreadStart
delegate instead. Additionally, you should be careful with subsequently modifying theudpData
local, since it is captured.Alternatively, if you don't mind using the thread-pool instead of spawning your own thread, you could use asynchronous delegates. For example: