Hello,

Below is the portion of my TCP server. The problem I am experiencing is that threads are not closed properly. My understanding was that after the given Sub completes, then the thread closes. In my program for some reason about 30% of the threads created, are never being closed. I am looking at the Task Manager and they just keep going up.

Can someone look over at my code and see if I am making any obvious mistakes? How can I find out and kill old/inactive threads?

Thanks!

Code:
Private Sub StartTCPListenerMultiThreaded()
	Dim localAddr As IPAddress = IPAddress.Parse(ip)
	TCPserver = New Sockets.TcpListener(localAddr, listeningPort)
	TCPserver.Start()			
	While True
		If TCPserver.Pending Then
			Dim t As Thread
			t = New Thread(AddressOf Me.acceptingThread)
			t.Start()
		End If
		System.Threading.Thread.Sleep(20)
	End While
End Sub

Private Sub acceptingThread()
	Dim client As TcpClient = TCPserver.AcceptTcpClient
	Dim stream As NetworkStream = client.GetStream
	client.ReceiveTimeout = 90000
	client.SendTimeout = 90000
	
	While client.Connected
		Dim bytes(1) As Byte
		Dim i As Int32
			i = stream.Read(bytes, 0, bytes.Length)
			While (i <> 0)
				'do something here with received payload
				If stream.DataAvailable = False Then
					Exit While
				End If
				i = stream.Read(bytes, 0, bytes.Length)
			End While	
	End While
	
End Sub