我创建一个TCP连接的服务器。 TCP连接在其自己的线程中运行无限期的时间。有没有一种很好的模式来允许安全关闭TcpListener和Client以及线程?以下是我到目前为止。正确的方法来中止一个封锁线程
private volatile bool Shudown;
void ThreadStart1()
{
TcpListener listener = null;
TcpClient client = null;
Stream s = null;
try
{
listener = new TcpListener(60000);
client = listener.AcceptTcpClient();
Stream s = client.GetStrea();
while(!Shutdown) // use shutdown to gracefully shutdown thread.
{
try
{
string msg = s.ReadLine(); // This blocks the thread so setting shutdown = true will never occur unless a client sends a message.
DoSomething(msg);
}
catch(IOException ex){ } // I would like to avoid using Exceptions for flow control
catch(Exception ex) { throw; }
}
}
catch(Exception ex)
{
LogException(ex);
throw ex;
}
finally
{
if(listener != null) listener.Close();
if(s != null) s.Close();
if(client != null) client.Close();
}
}
你的catch子句是多余的。这不是你的问题的解决方案,但它仍然是多余的。 – zmbq
你的权利。我编辑表明我的真实意图。 – Neal
在类似的说明中,你不应该这么做,因为这会重置你的堆栈跟踪。尝试使用'throw'代替。请参阅:http://stackoverflow.com/questions/178456/what-is-the-proper-way-to-re-throw-an-exception-in-c –