I have a WinForms application for a TCP-IP client. Once the client gets connected to a localhost server, I start a thread t1
, which enters in an infinite loop to keep receiving messages from the server.
When the server is not sending any message then the thread waits INFINITELY at the statement m_DeviceServerStream.Read(instream, 0, buffersize);
as shown in the code below.
Thread t1;
TcpClient m_DeviceClientSocket = new TcpClient();
NetworkStream m_DeviceServerStream = default(NetworkStream);
public void StartClient()
{
m_DeviceClientSocket.Connect(m_DeviceURL, m_DevicePort);
m_DeviceServerStream = m_DeviceClientSocket.GetStream();
t1 = = new Thread(KeepReceiveingMessages);
t1.Start();
}
public void StopClient() //On Stop Button-click
{
t1.Abort();
}
public void KeepReceiveingMessages()
{
while(true)
{
_dataServiceConnected.Waitone()
try
{
var buffersize = m_DeviceClientSocket.ReceiveBufferSize;
byte[] instream = new byte[buffersize];
m_DeviceServerStream.Read(instream, 0, buffersize) //THREAD T1 KEEP WAITING HERE TILL A MESSAGE IS RECEIVED FROM THE SERVER
}
catch(Exception e)
{
_dataServiceConnected.Reset(); //do not try to eneter again till we have a working connection
}
}
}
Question: If I want to close the Client application then, I want to finish the thread gracefully. But I found even if I call t1.Abort()
, the thread t1
keeps running (as shown in the Visual Studio Thread-Debug window). Aborting a thread is not a good practice, so how should I do end the thread?