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

北城余情 提交于 2019-12-21 05:14:12

问题


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;
}

回答1:


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.




回答2:


I've had good experiences using https://github.com/tejacques/AsyncBridge for async methods without Task.Run, although syntactically it looks somewhat similar, it is much safer.



来源:https://stackoverflow.com/questions/25513880/is-there-a-net-4-5-equivalent-to-storagefile-openasync

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!