I'm writing a class that communicates with a server using the TcpClient
class. Most of the methods I've written are intended to be used
synchronously and will block until they are completed. But these calls will
be made very seldom and between operations I would like to put the client
into a "listening mode" that will listen for other server messages. When
the client is ready to send/receive data again, take it back out of
listening mode and again begin synchronous operations. It's quite easy to
set up a BeginRead on the stream I created and have its callback process any
messages received from the server. But when I want to STOP listening and
start synchronous operations again I need to be able to cancel this. I
think the easiest way would be if I could just cancel the thread that I
started the BeginRead operation on. I'm sure there is a way to use the
IAsyncResult or it's WaitHandle to cancel the thread, but threading is not
my strongpoint and a solution is alluding me right now. Any assistance
would be appreciated. Here's the skeleton of what I'm going for.
private IAsyncResult ar;
private void Listen()
{
listenBuffer = new byte[1024];
ar = stream.BeginRead(listenBuffer, 0, listenBuffer.Length, new
AsyncCallback(ListenMessage), this);
}
private void ListenMessage(IAsyncResult ar)
{
// ..... interpret received message.
}
private void StopListen()
{
// ?????? ar...
}
Any help is appreciated,
Jacob