D
DaveR
I have a background thread to accept and process TCP/IP connections.
When the application shuts down I want to gracefully terminate it.
The thread will block in NetworkStream.Read() waiting for data. I
expected that shutting down the TcpListener would unblock the Read()
and cause an exception, or return 0 bytes. But it does not work.
Relevant parts of the code are shown below. If a client connects, the
stream blocks in its Read() method. If Stop() is then called from the
main thread, NetworkStream.Read() stays blocked even though the
TcpListener has stopped (and thus the underlying socket is closed).
I expect Read() to throw an IOException with an inner SocketException,
or at least for it to unblock and return 0 bytes. But it doesn't work.
Any suggestions would be appreciated.
private TcpListener _listener;
public void StartListening()
{
_listener = new TcpListener(endPoint);
_listener.Start();
Thread thread = new Thread(new ThreadStart(this.Process));
thread.Start();
}
public void StopListening()
{
_listener.Stop();
}
private void Process()
{
while (true)
{
try
{
TcpClient client = _listener.AcceptTcpClient();
NetworkStream strm = client.GetStream();
while (true)
{
int bytesRead = strm.Read(buf, 0, buf.Length);
// ... process ...
}
}
catch (IOException e)
{
// Expect a SocketException when the listener stops
}
}
}
When the application shuts down I want to gracefully terminate it.
The thread will block in NetworkStream.Read() waiting for data. I
expected that shutting down the TcpListener would unblock the Read()
and cause an exception, or return 0 bytes. But it does not work.
Relevant parts of the code are shown below. If a client connects, the
stream blocks in its Read() method. If Stop() is then called from the
main thread, NetworkStream.Read() stays blocked even though the
TcpListener has stopped (and thus the underlying socket is closed).
I expect Read() to throw an IOException with an inner SocketException,
or at least for it to unblock and return 0 bytes. But it doesn't work.
Any suggestions would be appreciated.
private TcpListener _listener;
public void StartListening()
{
_listener = new TcpListener(endPoint);
_listener.Start();
Thread thread = new Thread(new ThreadStart(this.Process));
thread.Start();
}
public void StopListening()
{
_listener.Stop();
}
private void Process()
{
while (true)
{
try
{
TcpClient client = _listener.AcceptTcpClient();
NetworkStream strm = client.GetStream();
while (true)
{
int bytesRead = strm.Read(buf, 0, buf.Length);
// ... process ...
}
}
catch (IOException e)
{
// Expect a SocketException when the listener stops
}
}
}