【发布时间】:2014-04-16 22:50:22
【问题描述】:
所以我创建了一个需要监听客户端连接的服务器,并且在我的服务器类的构造函数中:
class Server
{
private Thread listenerThread;
private TcpListener listener;
public Server()
{
this.listener = new TcpListener(IPAddress.Any, 5000);
listenerThread = new Thread(ListenMethod) { IsBackground = true };
listenerThread.Start();
}
private void ListenMethod()
{
listener.Start();
while (true)
{
TcpClient client = listener.AcceptTcpClient();
}
}
}
但是当我像这样在我的主服务器中创建服务器实例时:
class Program
{
static void Main(string[] args)
{
Server s = new Server();
}
}
由于 ListenMethod 运行和 while 循环,服务器应该保持打开状态,但程序似乎完成了构造函数并关闭了程序。
有什么想法吗?
谢谢:)
【问题讨论】:
-
为什么不让主线程成为服务器呢?当主线程什么都不做时创建后台线程似乎毫无意义。
标签: c# .net multithreading console-application