Passing object to stream fails - C #

I am trying to pass an object into my main thread, but it does not seem to work as I thought.

First I create Thread:

Thread thrUDP; 

Then I create an object that I will use to store the data I need:

 UDPData udpData; 

Now I initialize the object with the correct data. Configure a new thread and start it with the object passed to 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 want to start:

 private void SendStatus(UDPData data) { } 

I remember how I used Threads some time ago, and I'm sure that it wasn’t so difficult for them to transfer data, am I doing it wrong or just missing a piece of code?

Thanks!

+4
source share
2 answers

The ParameterizedThreadStart display adapter is declared as:

 public delegate void ParameterizedThreadStart(object obj); 

It is clear that this delegate is not compatible with your method signature, and there is no direct way to get System.Threading.Thread to work with an arbitrary type of delegation.

One of your options would be to use a compatible signature for the method and match:

 private void SendStatus(object obj) { UDPData data = (UDPData)obj; ... } 

Another option is to compose the problem with the C # compiler by creating a closure. For instance:

 new Thread(() => SendStatus(udpData)).Start(); 

Note that a ThreadStart delegate is used ThreadStart . In addition, you should be careful with the subsequent change to the local udpData , as it is committed.

Alternatively, if you don't mind using a thread pool instead of creating your own thread, you can use asynchronous delegates. For instance:

 Action<UDPData> action = SendStatus; action.BeginInvoke(udpData, action.EndInvoke, null); 
+3
source
 private void SendStatus(object data) { UDPData myData = (UDPData) data; } 
+1
source

All Articles