Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending a class as a parameter to a thread?

So I am trying to find a way to dynamically pass a class type to a thread, so it can recall the class that it was issued by, and thereby dynamically return data to that class again.

Here is what I am trying, where ServerClass is the class of this main function:

public static void Main()
{
    UDPClass clsUDP = new UDPClass();
    Thread clsUDPThread = new Thread(new ThreadStart(delegate() { clsUDP.UDPListen(64000, ServerClass); }));
    clsUDPThread.Start();
}

This is the receiving end, in the UDPClass:

public void UDPListen(int UDPPort, Type OldClass)
{
}

2 Answers

You can do a lot with code like this.

class X : BaseClass
{ 
   ...
}

class Y : X
{ 
    int yField;
}

...

int Main(BaseClass instance)
{ 
    if (instance is Y) (instance as Y).yField = 1;
}
like image 127
Jaapjan Avatar answered Feb 12 '26 14:02

Jaapjan


You need to change the line as follow:

Thread clsUDPThread = new Thread(new ThreadStart(delegate() { clsUDP.UDPListen(64000, typeof(ServerClass)); }));

Although, only accepting type will not solve your problem - you need to actually accept the instance (object) of the type (assuming you want to invoke instance methods/properties). The better way would be to accept an interface that your target type must implement.

EDIT:

Ok - here's how you would use an interface.

public interface IUDPListener
{
   void Notify(string status);
}

In UDP class,

public void UDPListen(int UDPPort, IUDPListener listner)
{
  ...
  listener.Notify("bla bla");
  ...
}

public class ServerClass : IUDPListener
{
   ...

   public void Notify(string status)
   {
     // Callback from thread
     ...
   }

   // Method that starts thread
   public void StartThread() 
   {
     UDPClass clsUDP = new UDPClass();
     Thread clsUDPThread = new Thread(new ThreadStart(delegate() { clsUDP.UDPListen(64000, this); }));
     clsUDPThread.Start();
   }   
}

You can also use a delegate for such notifications if its a simple one method callback. With interface, you can define multiple callbacks and also methods/properties to query the listener if needed. Here's the sample code using delegate

In UDP class,

public void UDPListen(int UDPPort, Action<string> callback)
{
  ...
  callback("bla bla");
  ...
}

In server class

public class ServerClass
{
   ...
    private void UdpCallback(string message)
    {
       ...
    }

    // code to start thread
    UDPClass clsUDP = new UDPClass();
    var clsUDPThread = new Thread(new ThreadStart(delegate() {clsUDP.UDPListen(64000, UdpCallback); }));
    clsUDPThread.Start();
like image 23
VinayC Avatar answered Feb 12 '26 16:02

VinayC