private void FinishHandshake(Exception e, AsyncProtocolRequest asyncRequest)
{
try
{
lock (this)
{
if (e != null)
{
SetException(e);
}
// Release read if any.
FinishHandshakeRead(LockNone);
// If there is a pending write we want to keep it's lock state.
int lockState = Interlocked.CompareExchange(ref _lockWriteState, LockNone, LockHandshake);
if (lockState != LockPendingWrite)
{
return;
}
_lockWriteState = LockWrite;
object obj = _queuedWriteStateRequest;
if (obj == null)
{
// We finished before Write has grabbed the lock.
return;
}
_queuedWriteStateRequest = null;
if (obj is LazyAsyncResult)
{
// Sync write is waiting on other thread.
((LazyAsyncResult)obj).InvokeCallback();
}
else
{
// Async write is pending, start it on other thread.
// Consider: we could start it in on this thread but that will delay THIS handshake completion
ThreadPool.QueueUserWorkItem(new WaitCallback(CompleteRequestWaitCallback), obj);
}
}
}
finally
{
if (asyncRequest != null)
{
if (e != null)
{
asyncRequest.CompleteUserWithError(e);
}
else
{
asyncRequest.CompleteUser();
}
}
}
}