private void ProcessMessages() { var incomingMessage = new byte[BufferSize]; _isBufferReady.Set(); try { // tell others that we are indeed processing messages. _isProcessingMessages.Set(); do { // we need to wait for the buffer to become available. _isBufferReady.WaitOne(); // now we claim the buffer _isBufferReady.Reset(); Task <int> readTask; readTask = _pipe.ReadAsync(incomingMessage, 0, BufferSize); readTask.ContinueWith( antecedent => { if (antecedent.IsCanceled || antecedent.IsFaulted || !IsConnected) { if (antecedent.IsCanceled) { Logger.Message("Client/Session ReadTask is Cancelled"); } if (antecedent.IsFaulted) { Logger.Message("Client/Session ReadTask is Faulted : {0}", antecedent.Exception.GetType()); } Disconnect(); return; } if (antecedent.Result > 0) { var rawMessage = Encoding.UTF8.GetString(incomingMessage, 0, antecedent.Result); var responseMessage = new UrlEncodedMessage(rawMessage); var rqid = responseMessage["rqid"].ToInt32(); // lazy log the response (since we're at the end of this task) Logger.Message("Response:[{0}]{1}".format(rqid, responseMessage.ToSmallerString())); try { var queue = ManualEventQueue.GetQueue(rqid); if (queue != null) { queue.Enqueue(responseMessage); } //else { // GS01 : Need to put in protocol version detection. //} } catch { } } // it's ok to let the next readTask use the buffer, we've got the data out & queued. _isBufferReady.Set(); }).AutoManage(); // this wait just makes sure that we're only asking for one message at a time // but does not throttle the messages themselves. // readTask.Wait(); } while (IsConnected); } catch (Exception e) { Logger.Message("Connection Terminating with Exception {0}/{1}", e.GetType(), e.Message); } finally { Logger.Message("In ProcessMessages/Finally"); Disconnect(); } }