【发布时间】:2016-05-15 02:10:27
【问题描述】:
我刚刚学习 C# 中的线程,出现了一个问题。
我有一个 TCP-Server-Class,它接受连接并将它们传递给 TCP-Client-Class。
代码大致如下:(dummy code)
Class TcpServer
{
public static Main(string[] args)
{
while(true)
{
//I create a new instance of my "TCP-Client-Class" and pass the accepted connection to the constructor
ConnectionHandler client = new ConnectionHandler(TCPListner.acceptconnections);
//create a new Thread to handle that connection
Thread client1 = new Thread (client.handleConnection()); //and start handling it
client.start;
//Do some other stuff for protokolling
do.someOtherStuff;
// and then wait for a new connection
}
}
//Some other Methods etc.
}
Class ConnectionHandler
{
//Constructor in which a connection TCPclient connection has to be passed
public ConnectionHandler(TCPclient client)
{
//Do stuff
}
//Method to handle connection
public void handleConnections()
{
//Open streams
//.
//.
//.
//close streams
//close connections
}
}
现在回答我的问题:
a) 在达到“关闭连接”部分后是否必须再次关闭该线程?
b) 要关闭一个线程,我是否只需要在我的主类中调用 .join 方法,或者还有什么我需要注意的。
c) 如果出现错误,我可以简单地离开“handleConnection()”方法并关闭该线程(ofc 并进行适当的错误处理)吗?
d) 删除“client”引用或“client1”引用是否重要?还是只是被垃圾收集器消耗掉了?
【问题讨论】:
-
也许出于教育目的,直接使用 Thread 类很有趣,但出于其他目的,我建议您查看线程池甚至 C#6 中的异步功能
-
@Rafa 好吧,那是我第二次阅读线程池,我现在肯定会阅读它:D
标签: c# multithreading sockets tcpclient tcplistener