我为 C# 编写了一个包装类,Stream
因为我希望它能够在通过 ReadAsync() 读取数据时向流中注入数据并调用函数。但是“注入”部分不起作用,我不知道为什么。
class ExtendedStream : Stream
{
private readonly Stream _originalStream;
private readonly Action<byte[]> _readCallback;
private ManualResetEvent dataInjected = new ManualResetEvent(false);
private List<byte> data = new List<byte>();
private int pos = 0;
public ExtendedStream(Stream originalStream, Action<byte[]> readCallback)
{
_originalStream = originalStream;
_readCallback = readCallback;
}
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken)
{
var read = await _originalStream.ReadAsync(buffer, offset, count, cancellationToken);
_readCallback(buffer);
return read;
}
public void Inject(string text)
{
data.AddRange(new UTF8Encoding(false).GetBytes(text));
dataInjected.Set();
}
private IEnumerable<byte> GetBytes(int count)
{
int returned = 0;
while (returned == 0)
{
if (pos < data.Count)
{
while (pos < data.Count && returned < count)
{
yield return data[pos];
pos += 1; returned += 1;
}
}
else
{
dataInjected.Reset();
dataInjected.WaitOne();
}
}
}
public override int Read(byte[] buffer, int offset, int count)
{
var bytes = GetBytes(count).ToArray();
for (int i = 0; offset + i < buffer.Length && i < bytes.Length; i++)
{
buffer[offset + i] = bytes[i];
}
return bytes.Length;
}
public override void Write(byte[] buffer, int offset, int count)
{
_originalStream.Write(buffer, offset, count);
}
public override bool CanRead
{
get { return _originalStream.CanRead; }
}
public override bool CanSeek
{
get { return _originalStream.CanSeek; }
}
public override bool CanWrite
{
get { return _originalStream.CanWrite; }
}
public override void Flush()
{
_originalStream.Flush();
}
public override long Length
{
get { return _originalStream.Length; }
}
public override long Position
{
get { return _originalStream.Position; }
set { _originalStream.Position = value; }
}
public override long Seek(long offset, SeekOrigin origin)
{
return _originalStream.Seek(offset, origin);
}
public override void SetLength(long value)
{
_originalStream.SetLength(value);
}
}
然后我正在使用 XmlReader 读取流,如下所示。
using (XmlReader xmlReader = XmlReader.Create(_extendedStream, new XmlReaderSettings() { Async = true }))
{
while (await xmlReader.ReadAsync())
{
switch (xmlReader.NodeType)
{
case XmlNodeType.EndElement:
if (xmlReader.LocalName.Equals("test"))
{
_log.Debug("</test> injected!");
}
break;
default:
break;
}
}
如果我调用,则永远不会注入数据_extendedStream.Inject("</test>")
。有谁知道为什么?