I think this is what PIEBALDconsult was referring to:
public void StartServer(bool InThread = false)
{
if (InThread)
{
Thread t = new Thread(it => StartServer((bool)it));
t.Start(false);
}
else
{
TcpListener listener = new TcpListener(IPAddress.Any, Port);
while (true)
{
if (listener.Pending())
{
TcpClient client = listener.AcceptTcpClient();
if (OnClientConnected != null)
OnClientConnected(client);
}
}
}
}
The lambda in the
Thread
constructor is required because the
ParameterizedThreadStart
delegate to that constructor needs the argument to be type
object
.
Edit: MTH
As PIEBALDconsult noted in the comments below. The thread creation can be simplified a bit:
if (InThread)
{
Thread t = new Thread(() => StartServer(false));
t.Start();
}
else
Or, if you just want to start the thread and then forget about it:
if (InThread)
{
new Thread(() => StartServer(false)).Start();
}
else
but you won't be able to do
anything to the thread after that.
(That's pretty much like having the local variable
t
go out of scope right after starting the thread!)