Reputation: 11502
Say I open a FileStream for asynchronous I/O (using FileOptions.Asynchronous), from a quick test it seems I can do normal synchronous I/O on it and the results are the same as if I had opened it without asking for asynchronous.
Are there any hidden gotchas in doing this? I presume the reason I need to pass in a special flag to indicate asynchronous is because there is some extra overhead.
The reason I want do to this is simply because of code reuse - I already have a function that opens the file asynchronously which I want to call but the calling code is synchronous.
Upvotes: 1
Views: 326
Reputation: 101613
If you provide FileOptions.Asynchronous
- FileStream
will use windows overlapped IO. That in simplified terms means OS will notify application when read\write operation is complete via IO completion port, without application thread being blocked waiting for that specific operation to complete.
When you execute synchronous operation on such FileStream
- still the same overlapped IO is used and then your current thread is blocked waiting for it to complete, basically defeating all benefits of overlapped IO.
This overlapped IO has some overhead compared to synchronous IO, so, overall, executing synchronous operations on FileStream
with FileOptions.Asynchronous
does have some overhead. However, if this overhead is significant for your specific situation can only be measured by you.
Side note: if you are executing asynchronous operations on FileStream
without that flag - regular synchronous IO is used and thread pool thread basically waiting for it to complete, making the whole thing quite useless (except if you only do that for something like avoiding UI thread blocking and not for increased throughput).
So in short, if you can, open file for synchronous or asynchronous access and then actually access it in that way. But if for some reason you can't - there will be some overhead in both cases, but it will still work fine.
Upvotes: 2