.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