public async Task WriteAsync(IProtocolMessage msg, CancellationToken token = default) { Debug.WriteLine($"Writing protocol message {msg}"); Memory <byte> buf; var estSize = 4096; int size; do { buf = _writer.GetMemory(estSize); try { size = msg.Serialize(buf); } catch (ArgumentException) { estSize *= 2; continue; } if (estSize > 65536) { throw new ArgumentException("Protocol message is too large"); } _writer.Advance(size); await _writer.FlushAsync(token); return; } while (true); }