112 lines
3.0 KiB
C#
Raw Normal View History

2020-04-21 21:17:34 +02:00
using System;
using System.IO;
2020-04-21 21:42:51 +02:00
using System.Net.Sockets;
using System.Threading;
2020-04-21 21:17:34 +02:00
namespace Capnp.Util
{
2020-04-21 21:42:51 +02:00
internal class AsyncNetworkStreamAdapter : Stream
2020-04-21 21:17:34 +02:00
{
2020-04-21 22:23:08 +02:00
// Async I/O pays off for large payloads. Perf. profiling gave a threshold around 200kB
const int DefaultAsyncThreshold = 200000;
2020-04-21 21:42:51 +02:00
readonly NetworkStream _stream;
2020-04-21 22:23:08 +02:00
readonly int _asyncThreshold;
2020-04-21 21:17:34 +02:00
readonly object _reentrancyBlocker = new object();
2020-04-21 22:23:08 +02:00
Exception? _bufferedException;
2020-04-21 21:17:34 +02:00
2020-04-21 22:23:08 +02:00
public AsyncNetworkStreamAdapter(Stream stream, int asyncThreshold)
2020-04-21 21:17:34 +02:00
{
2020-04-21 22:23:08 +02:00
_asyncThreshold = asyncThreshold;
2020-04-21 21:42:51 +02:00
_stream = stream as NetworkStream ?? throw new ArgumentException("stream argument must be a NetworkStream");
2020-04-21 21:17:34 +02:00
}
2020-04-21 22:23:08 +02:00
public AsyncNetworkStreamAdapter(Stream stream): this(stream, DefaultAsyncThreshold)
{
}
2020-04-21 21:17:34 +02:00
public override bool CanRead => true;
public override bool CanSeek => false;
public override bool CanWrite => true;
public override long Length => 0;
public override long Position
{
get => 0;
set => throw new NotSupportedException();
}
public override void Flush()
{
2020-04-21 22:23:08 +02:00
_stream.FlushAsync();
//_stream.Flush();
2020-04-21 21:17:34 +02:00
}
public override int Read(byte[] buffer, int offset, int count)
{
2020-04-21 21:42:51 +02:00
return _stream.Read(buffer, offset, count);
2020-04-21 21:17:34 +02:00
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
2020-04-21 21:42:51 +02:00
//void WriteCallback(IAsyncResult ar)
//{
// try
// {
// _stream.EndWrite(ar);
// }
// catch (Exception exception)
// {
// Volatile.Write(ref _bufferedException, exception);
// }
//}
2020-04-21 21:17:34 +02:00
public override void Write(byte[] buffer, int offset, int count)
{
2020-04-21 21:42:51 +02:00
_stream.WriteAsync(buffer, offset, count);
//var exception = Volatile.Read(ref _bufferedException);
//if (exception != null)
//{
// Dispose();
// throw exception;
//}
2020-04-21 22:23:08 +02:00
//if (count >= _asyncThreshold)
// _stream.BeginWrite(buffer, offset, count, WriteCallback, null);
//else
// _stream.Write(buffer, offset, count);
2020-04-21 21:17:34 +02:00
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
lock (_reentrancyBlocker)
{
try
{
2020-04-21 21:42:51 +02:00
_stream.Dispose();
2020-04-21 21:17:34 +02:00
}
catch
{
}
}
}
base.Dispose(disposing);
}
}
}