kevin
kevin

Reputation: 275

Is Asynchronous file IO thread safe?

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.

Upvotes: 3

Views: 924

Answers (3)

Tal Aloni
Tal Aloni

Reputation: 1519

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.

Upvotes: 1

Teoman Soygul
Teoman Soygul

Reputation: 25742

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.

Upvotes: 4

None
None

Reputation: 41

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#.

Upvotes: 4

Related Questions