我想用外部类中实现的方法启动Thread
,并且我需要将此方法引用传递给某些外部属性。
问题出在这里
Thread t = new Thread(Agent.Activate(agentParameters, ref tcpListener));
Visual Studio说Acvivate
方法应返回Thread
。但是下面的例子不应该。
我使用此示例但它没有帮助https://msdn.microsoft.com/en-us/library/system.threading.thread.setdata(v=vs.110).aspx。这是我的代码
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();
}
}
答案 0 :(得分:3)
您必须将您的方法作为委托传递给新线程:
Thread t = new Thread(() => Agent.Activate(agentParameters, ref tcpListener));