How to prevent this issue when writing data to the client Asynchronously
The BeginWrite method cannot be called when another write operation is pending
MYCODE
public async void Send(byte[] buffer)
{
if (buffer == null)
return;
await SslStream.WriteAsync(buffer, 0, buffer.Length);
}
It is important to understand exactly what the await keyword does:
When you call Send with some non null buffer you will get to
Using await you block the execution only in the Send method, but the code in the caller continues to execute even if the WriteAsync has not completed yet. Now if the Send method is called again before the WriteAsync has completed you will get the exception that you have posted since SslStream does not allow multiple write operations and the code that you have posted does not prevent this from happening.
If you want to make sure that the previous BeginWrite has completed you have to change the Send method to return a Task
and wait for it’s completion by calling it using await like:
This should work if you do not attempt to write data from multiple threads.
Also here is some code that prevents write operations from multiple threads to overlap (if properly integrated with your code). It uses an intermediary queue and the Asynchronous Programming Model(APM) and works quite fast.
You need to call EnqueueDataForWrite to send the data.