是否有一个等同于.NET 4.5:Storagefile.Openasync有一个、NET、Storagefile、Openasync

2023-09-03 13:42:52 作者:Absurd

我爱上了异步和等待,但我不知道如何等待一个文件,而无需使用Task.Run开放。似乎是在WRT 。哪里是.NET 4.5相同呢?我问,因为如果我在远程机器上访问UNC共享这有阻止了很长的时间,如果机器被关闭或不响应由于某种原因,网络请求的潜力。这似乎是这么大了点。

 使用(的FileStream流=等待Task.Run(()=>新建的FileStream(@C:\ TEMP \的text.txt,FileMode.OpenOrCreate,FileAccess.Read, FileShare.Read,4096,真正的)))
{
  byte []的bytesToRead =新的字节[stream.Length]
  等待stream.ReadAsync(bytesToRead,0,bytesToRead.Length).ConfigureAwait(假);
  返回bytesToRead;
}
 

解决方案

不幸的是,即使文件打开是异步的,在设备驱动程序级别,有一个异步打开文件没有的Win32 API。所以这就是为什么没有.NET同等学历;我不知道是肯定的,但我怀疑的WinRT API由它排队到线程池伪造异步操作。

所以,最好的办法是做一个类似的解决方法:使用 Task.Run 。我想换行所有的的FileStream code。在 Task.Run ,虽然。

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;
}
Wolf CMS 新旧两个版本中的文件上传漏洞分析

解决方案

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.