1

i am facing an annoying problem with SslStream.WriteAsync

here is the code

public void Send(PacketWriter writer)
{
    var buffer = writer.GetWorkspace();

    _sslStream.WriteAsync(buffer, 0, buffer.Length);
}

When writing the data at extremely high speed it tells me

The beginwrite method cannot be called when another write operation is pending

[NOTE] : I mean by high speed something like this

for (var i = 0 ; i <= 1000; i++)
{
    Send(somedata);
}
Daniel Eugen
  • 2,712
  • 8
  • 33
  • 56

2 Answers2

1

You must wait until the previous asynchronous write has finished.

Change your send method to return a Task:

public Task Send(PacketWriter writer)
{
    var buffer = writer.GetWorkspace();
    return _sslStream.WriteAsync(buffer, 0, buffer.Length);
}

Make the calling method async, then await until each send operation completes:

for (var i = 0 ; i <= 1000; i++)
{
    await Send(somedata);
}
Julien Lebosquain
  • 40,639
  • 8
  • 105
  • 117
0

May be try this-

 private static void send_data(SslStream socket_stream, byte[] data)
        {
          Task task = new Task(() => { socket_stream.Write(data, 0, data.Length); });
          task.RunSynchronously();
          task.Wait();
        }

This will make sure all the messaages are sent in oderly manner without any exception

user2288650
  • 412
  • 1
  • 6
  • 23