我编写了以下函数来实现超时功能NetworkStream
的异步读取函数(BeginRead
and EndRead
)。在我注释掉该行之前它工作正常Trace.WriteLine("bytesRead: " + bytesRead);
. Why?
private int SynchronousRead(byte[] buffer, int count)
{
int bytesRead = 0;
bool success = false;
IAsyncResult result = null;
result = _stream.BeginRead(
buffer, 0, count,
delegate(IAsyncResult r)
{
bytesRead = _stream.EndRead(r);
},
null);
success = result.AsyncWaitHandle.WaitOne(_ioTmeoutInMilliseconds, false);
if (!success)
{
throw new TimeoutException("Could not read in the specfied timeout.");
}
//If I remove this line, bytesRead is always 0
Trace.WriteLine("bytesRead: " + bytesRead);
return bytesRead;
}
以防万一您想知道,我必须这样做,因为我最终需要以 .Net Compact Framework 3.5 为目标,而它不支持NetworkStream.ReadTimeout
and NetworkStream.WriteTimeout
特性。
一个有趣的线程错误。 bytesRead 变量已赋值after等待句柄已发出信号。有两件事可能会出错:方法在赋值之前返回。或者线程读取过时的值,因为它们在 WaitOne() 调用之后没有内存屏障。 Trace 语句解决了这个问题,因为它延迟了主线程足够长的时间以允许写入变量。它有一个内部锁来确保缓存是一致的。
您将需要一个额外的 AutoResetEvent 来指示 bytesRead 变量已写入。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)