Is asynchronous file IO 开发者_运维百科like FileStream.BeginWrite thread safe? If not, then it need to wrap with "SyncLock", that's mean it is still blocking thread.
FileStream.BeginWrite
already starts a new thread to access the files. You don't need to start the FileStream.BeginWrite
on a separate thread (because that will be thread in a thread). On the other hand, multiple FileStream.BeginWrite
functions should not be accessing the same file at the same time.
Also if the resource is accessed by multiple threads, it means it is a shared resource and there are plentiful of resources about using them in c#.
FileStream.BeginRead / BeginWrite implementations are asynchronous, but their usage of overlapped I/O is not done in a thread-safe manner.
You can see that BeginRead / BeginWrite do not accept the read / write file position as a parameter, so operations on other threads (such as Seek) may cause the read / write to be at the wrong file position.
If you still aren't convinced, Microsoft's FileStream implementation explicitly specify "This isn't threadsafe." in a comment inside BeginReadCore & BeginWriteCore.
Bottom line: if you need overlapped I/O that is thread-safe, you'll have to use P/Invoke with ReadFile / WriteFile.
精彩评论