so i am just learning about Threads in C# and a question arose.
I have a TCP-Server-Class wich accepts connections and passes them to a TCP-Client-Class.
The code roughly looks like this:
(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 konstruktor
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 ect.
}
Class ConnectionHandler
{
//Konstruktor in wich 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
}
}
Now to my questions:
a) Is it obligotory to close that Thread again, after it reached the "close connection" part?
b) To close a thread do i just have to call the .join Method in my main class or is there anything else i have to take care about.
c) Incase of an error, can i just simply leave the "handleConnection()" method and close that thread (ofc with apropriate error-handling)?
d) Is it important to drop the "client" reference or the "client1" reference? Or is it just consumed by the garbage collector?
Well, it's entirely fine to let the thread just complete normally. If the top-level call of a thread throws an exception, it may take down the process, depending on how the CLR is configured. It's usually better to have a top-level error handler to log the error and move on.
However, you should consider what you want to happen on shutdown:
while (true)
loop should be changed to allow some mechanism for shutting downJoin
on them (probably with a timeout) to allow them to complete before the server finishes. However, you want to remove a thread from that collection when it completes. This sort of thing gets fiddly fairly quickly, but is definitely doable.As an aside, it's more common to use a thread-pool for this sort of thing, rather than creating a brand new thread for each request.
See more on this question at Stackoverflow