.Net FileStream可以接受以下多线程调用模式吗?FileStream的同步要求(开始/结束)(读/写)
的多个线程调用这样的方法:
ulong offset = whatever; // different for each thread
byte[] buffer = new byte[8192];
object state = someState; // unique for each call, hence also for each thread
lock(theFile)
{
theFile.Seek(whatever, SeekOrigin.Begin);
IAsyncResult result = theFile.BeginRead(buffer, 0, 8192, AcceptResults, state);
}
if(result.CompletedSynchronously)
{
// is it required for us to call AcceptResults ourselves in this case?
// or did BeginRead already call it for us, on this thread or another?
}
其中AcceptResults
是:
void AcceptResults(IAsyncResult result)
{
lock(theFile)
{
int bytesRead = theFile.EndRead(result);
// if we guarantee that the offset of the original call was at least 8192 bytes from
// the end of the file, and thus all 8192 bytes exist, can the FileStream read still
// actually read fewer bytes than that?
// either:
if(bytesRead != 8192)
{
Panic("Page read borked");
}
// or:
// issue a new call to begin read, moving the offsets into the FileStream and
// the buffer, and decreasing the requested size of the read to whatever remains of the buffer
}
}
我很困惑,因为文件似乎我不清楚。例如,FileStream类说:
此类型的任何公共静态成员都是线程安全的。任何实例成员不保证是线程安全的。
但的BeginRead的文件似乎考虑在飞行中有多个读取请求:
同时进行多个异步请求呈现请求完成顺序不确定。
允许多个读取在飞行中吗?写?这是确保呼叫Seek和呼叫BeginRead
之间的流的Position
位置的适当方式吗?或者该锁需要一直保持到EndRead
,因此一次只能在一次读取或写入数据?
据我所知,回调将发生在另一个线程上,我的处理state
,buffer
处理,允许在飞行中读取多个。
此外,有没有人知道在文档的哪里找到这些问题的答案?或者知道某人写的文章?我一直在寻找,找不到任何东西。
相关文章:
FileStream class
Seek method
BeginRead method
EndRead
IAsyncResult interface
编辑了一些新的信息
使用Reflector快速检查显示BeginRead确实将流位置捕获到每个调用状态(NativeOverlapped结构的某些字段)。看起来,EndRead并未咨询流的位置,至少没有以任何明显的方式。这显然不是确定的,因为它可能不是明显的方式,或者它可能不被底层的本地API支持。
+1写得很好的问题。 – SLaks 2010-04-02 01:43:18