How to cancel Async read from socket?

  • Thread starter Thread starter John Hynes
  • Start date Start date
J

John Hynes

Hi,

I have a CompactFramework application that has a socket open to a server
with an asynchronous read to read notification messages from the server and
display them to the user.

I am using NetworkStream.BeginRead to start the read operation.

The problem I have is that when the user chooses to exit the application and
I call NetworkStream.Close and Socket.Shutdown, the application hangs on
exit. The debugger shows that there is one thread left running - the worker
thread for the async read which is still trying to read from the socket.

How do I cancel this read? If I call NetworkStream.EndRead from my main
thread, this just hangs waiting for the read to complete. Unfortunaterly, on
the PocketPC the application window is still visible on the screen and never
goes away.

Thanks
John
 
Did you try Socket.Close, I dont know which stream you are using here ! If
you call methods on teh stream it might be possible that they dont call the
methods on the socket !

Joe Robe
 
Yes, shutdown code I have is:

networkStream.Close()
socket.Shutdown( SocketShutdown.Both );
socket.Close();

this thread then exits, but one thread hangs, call stack for the thread
that hangs is:

System.dll!System.Net.OSSOCK.recv
System.dll!System.Net.Sockets.Socket.ReceiveNoCheck
System.dll!System.Net.Sockets.Socket.ReceiveAsyncRequest.doRequest
System.dll!AsyncRequest.handleRequest
System.dll!System.Net.Sockets.Socket.WorkerThread.doWork
System.dll!System.Net.Sockets.Socket.WorkerThread.doWorkI
mscorlib.dll!System.Threading.ThreadPool.WorkItem.doWork
mscorlib.dll!System.Threading.Timer.ring

John
 
Yes, shutdown code I have is:

networkStream.Close()
socket.Shutdown( SocketShutdown.Both );
socket.Close();

this thread then exits, but one thread hangs, call stack for the thread
that hangs is:

System.dll!System.Net.OSSOCK.recv
System.dll!System.Net.Sockets.Socket.ReceiveNoCheck
System.dll!System.Net.Sockets.Socket.ReceiveAsyncRequest.doRequest
System.dll!AsyncRequest.handleRequest
System.dll!System.Net.Sockets.Socket.WorkerThread.doWork
System.dll!System.Net.Sockets.Socket.WorkerThread.doWorkI
mscorlib.dll!System.Threading.ThreadPool.WorkItem.doWork
mscorlib.dll!System.Threading.Timer.ring

John
 
I don't know the answer to your particular question.
however, reading sample from many people (including microsoft peoples) it
appear that to do async process (like on socket) they simply create a
reader/write socket and return, and to kill it they abort the thread.
therefore I would suggest you NOT to rely on default async behavior but to
implement yours.
and to exit by aborting your thread.
 
Back
Top