Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a .NET 4.5 equivalent to: Storagefile.Openasync

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;
}
like image 951
Mike Barry Avatar asked Mar 18 '23 15:03

Mike Barry


1 Answers

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.

like image 82
Stephen Cleary Avatar answered Apr 02 '23 21:04

Stephen Cleary