99 lines
2.4 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 21:42:51 +02:00
readonly NetworkStream _stream;
2020-04-21 21:17:34 +02:00
readonly object _reentrancyBlocker = new object();
2020-04-21 21:42:51 +02:00
//Exception? _bufferedException;
2020-04-21 21:17:34 +02:00
2020-04-21 21:42:51 +02:00
public AsyncNetworkStreamAdapter(Stream stream)
2020-04-21 21:17:34 +02:00
{
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
}
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 21:42:51 +02:00
_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;
//}
//_stream.BeginWrite(buffer, offset, count, WriteCallback, null);
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);
}
}
}