【发布时间】:2014-12-03 08:15:30
【问题描述】:
这是一个非常简单的问题,但如果不与某人交谈,我似乎无法弄清楚。
我需要一个像 MemoryStream 这样的流,它会在读取时异步阻塞,直到有要读取的内容或超时。
更新: 好的。我已经放弃了,自己写了Wrapper类,但是EndRead总是返回0。请看下面的代码。 (不提供面向任务的解决方案。)
public class BlockingMemoryStream : MemoryStream
{
ManualResetEventSlim isReadReady = new ManualResetEventSlim(false);
public override void Write(byte[] buffer, int offset, int count)
{
base.Write(buffer, offset, count);
//base.Position = offset; //I do not know if I need this!!!!
isReadReady.Set();
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
IAsyncResult result = base.BeginRead(buffer, offset, count, callback, state);
return result;
}
public override int EndRead(IAsyncResult asyncResult)
{
isReadReady.Wait(/*600000*/);
int aa = base.EndRead(asyncResult);
return aa;
}
}
【问题讨论】:
-
上下文不清楚或不明显。它将如何写入?
-
请查看 C.Evenhuis 代码。那就是我要避免的代码。
-
如果您真的只想要一个涉及 .NET 本身现有实现的答案,我认为您不会得到这个答案。一个简单的启用超时的
Stream包装器可以在没有太多麻烦的情况下实现(尽管有当前的答案),但我想如果你只对.NET 中已经存在的东西感兴趣,那么提供它是没有意义的。
标签: c# asynchronous stream