private Task ProcessMessages(ITransportConnection connection, Func <Task> postReceive = null) { var tcs = new TaskCompletionSource <object>(); Action <Exception> endRequest = (ex) => { Trace.TraceInformation("DrainWrites(" + ConnectionId + ")"); // Drain the task queue for pending write operations so we don't end the request and then try to write // to a corrupted request object. WriteQueue.Drain().Catch().ContinueWith(task => { if (ex != null) { tcs.TrySetException(ex); } else { tcs.TrySetResult(null); } CompleteRequest(); Trace.TraceInformation("EndRequest(" + ConnectionId + ")"); }, TaskContinuationOptions.ExecuteSynchronously); if (AfterRequestEnd != null) { AfterRequestEnd(); } }; ProcessMessages(connection, postReceive, endRequest); return(tcs.Task); }