Dimi Dimi - 1 month ago 7
C# Question

Start a Thread from different class and parameters

I would like to start the

Thread
with methods implemented in a external class and as well as I need to pass to this method reference to some external property.

The problem is here

Thread t = new Thread(Agent.Activate(agentParameters, ref tcpListener));


Visual Studio say that
Acvivate
method should return
Thread
. But by example below it should not.

I use this example but it does not help https://msdn.microsoft.com/en-us/library/system.threading.thread.setdata(v=vs.110).aspx. Here is my code

class TCPListenerManager
{
TcpListener tcpListener;

public TCPListenerManager(HostListenerItem hostListenerItem)
{
tcpListener = new TcpListener(IPAddress.Parse(hostListenerItem.IP4), hostListenerItem.Port);

for (int i = 0; i < hostListenerItem.ClientsMax; i++)
{
var agentParameters = new AgentParameters();
Thread t = new Thread(Agent.Activate(agentParameters, ref tcpListener));
t.Start();
}
}

} // end of class DeviceAgent


class Agent
{
[ThreadStaticAttribute]
static int threadSpecificData;

static public AgentParameters Parameters;

public static void Activate(AgentParameters agentParameters, ref TcpListener tcpListener)
{
Parameters = agentParameters;
threadSpecificData = Thread.CurrentThread.ManagedThreadId;

var socket = tcpListener.AcceptSocket();
if (socket.Connected)
{
//
// logger.Info("Socket.Connected on" + socketParameters.HostListenerItem.Name + " " + socketParameters.HostListenerItem.Url);
}
}
} // end of Agent


class AgentParameters
{
public HostListenerItem HostListenerItem { get; set; }

public AgentParameters()
{
HostListenerItem = new HostListenerItem();
}
}

Answer

You have to pass your method as a delegate to the new thread:

Thread t = new Thread(() => Agent.Activate(agentParameters, ref tcpListener));