I'm falling in love with async and await, however I cannot figure out how to await a file open without using Task.Run. There seems to be an API in WRT. Where is the .NET 4.5 equivalent? I ask because if i'm accessing a UNC share on a remote machine this has the potential to block for a very long time if the machine is down or not responding to network requests for some reason. It seems like such a big over site.
using (FileStream stream = await Task.Run(() => new FileStream(@"c:\temp\text.txt", FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read, 4096, true)))
{
byte[] bytesToRead = new byte[stream.Length];
await stream.ReadAsync(bytesToRead, 0, bytesToRead.Length).ConfigureAwait(false);
return bytesToRead;
}
Unfortunately, even though file opens are asynchronous at the device driver level, there is no Win32 API for an asynchronous file open. So that's why there's no .NET equivalent; I don't know for sure but I suspect that the WinRT API is faking an asynchronous operation by queueing it to the thread pool.
So, the best solution is to do a similar workaround: use Task.Run
. I'd wrap all the FileStream
code in Task.Run
, though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With