tags:

views:

56

answers:

1

I have a socket wrapper class that sends and recieves messages with a server (specifically commands, responses, and notifications). I also have a consuming class that serializes the commands into text to send through the wrapper. My problem is that when a command is sent, I need to wait until I get a message back with a particular header. When I do this, the consuming class locks as I am using ManualResetEvent.WaitOne that is set by my receiving method. The reason it's a problem when my consuming class locks is that another message might be received in the meantime and I cannot process it. Is there any way to lock a specific object so my class can still respond to other events?

Send method:

    _waitingCommands.Enqueue(command);
    String commandText = command.ToString();
    _socket.Send(commandText);

Receive method:

if (response.Header.Type == Messages.MessageType.Response)
{
   if (command.Response == null)
      command.Response = response;

   _waitingCommands.Dequeue();
   command.Finished.Set();
}
A: 

Use socket.BeginSend and socket.BeginReceive. These will spin off seperate threads that will allow your main thread to continue processing. Once the data is sent or recieved, the methods you hooked up to the BeginSend/BeginReceive method will fire, in logical order.

Begin Send

BeginReceive

George