Sending a class as a parameter to a stream?

So, I'm trying to find a way to dynamically pass a class type to a stream, so it can recall the class that was released, and thereby dynamically return the data back to this class again.

Here is what I am trying, where ServerClass is a class of this core 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 side in UDPClass:

public void UDPListen(int UDPPort, Type OldClass)
{
}
+3
source share
3 answers

You can do a lot with this code.

class X : BaseClass
{ 
   ...
}

class Y : X
{ 
    int yField;
}

...

int Main(BaseClass instance)
{ 
    if (instance is Y) (instance as Y).yField = 1;
}
+1
source

You need to change the line as follows:

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

, - () ( , / ). , .

EDIT:

- .

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

UDP

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();
   }   
}

, . , / , .

UDP

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

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();
+1

You can use ParameterizedThreadStart to call a method with parameters in a new thread.

public static void Main()
{
    UDPClass.UDPListenParameters threadParameters = new UDPClass.UDPListenParameters();
    threadParameters.UDPPort = 64000;
    threadParameters.OldClass = this.GetType();

    UDPClass clsUDP = new UDPClass();
    Thread clsUDPThread = new Thread(new ParameterizedThreadStart(clsUDP.UDPListen));

    clsUDPThread.Start(threadParameters);
}

public class UDPClass
{
    public void UDPListen(object parameter)
    {
        UDPListenParameters parameters = (UDPListenParameters)parameter;
        // parameters.UDPPort
        // parameters.OldClass
    }

    public class UDPListenParameters
    {
        public int UDPPort;
        public Type OldClass;
    }
}

But, as VinayC pointed out, you will need to pass a reference to the server class instead of the type in order to be able to use it.

0
source

All Articles