使用异步方法无效里面等待 [英] Using async await inside void method

查看:277
本文介绍了使用异步方法无效里面等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有签名方法我不能改变。它应该是

I have method with signature I cannot change. It should be

protected override void OnInitialize()

使用Windows 8地铁API,我需要检查文件是否存在并读取它,这NoSignatureChange方法中。
使用PlainOldCSharp,我就喜欢写东西。

Using Windows 8 Metro API I need to check if file exists and read it, inside this NoSignatureChange method. Using PlainOldCSharp, I would write something like

protected override void OnInitialize()
{
  ...
  try
  {
    var file = folder.OpenFile(fileName);
    fileExists=true;
  }
  catch(FileNotFoundException)
  {
    fileExists=false
  }
}

记住,在 Windows 8的API唯一方法来检查文件是否存在正在处理FileNotFoundException异常
此外,在Windows 8 API的所有FileIO专注API是异步的,所以我只有file.OpenFileAsync方法。

Remember, in Windows 8 API only way to check if file exists is handling FileNotFoundException Also, in Windows 8 API all FileIO API is async, so I have only file.OpenFileAsync method.

所以,问题是:我应该如何编写使用folder.OpenFileAsync方法在Windows 8 API此code,而不改变包含方法签名

推荐答案

您仍然可以使无效异步方法:

You can still make a void method async:

protected async void CannotChangeSignature()
{
    ...
}

有效的返回类型异步方法是:

Valid return types for an async method are:


  • 无效

  • 任务

  • 任务< T>

  • void
  • Task
  • Task<T>

不过,如果你想让它的真正的块,那么你基本上对抗的平台 - 整点是的避免的阻塞

However, if you want to make it actually block, then you're basically fighting against the platform - the whole point is to avoid blocking.

您说你不能更改签名 - 但是如果你靠这个堵那么你的获得的改变你进场编码的方式

You say you can't change the signature - but if you're relying on this blocking then you've got to change the way you approach coding.

在理想情况下,你应该更改签名,以任务&LT;布尔&GT;

Ideally you should change the signature to Task<bool>:

protected async Task<bool> CannotChangeSignature()
{
  ...
  try
  {
    await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
    return true;
  }
  catch(FileNotFoundException)
  {
    return false;
  }
}

编辑:如果你的真正的需要阻断一个,你只需要调用 AsTask()等待(),赶 AggregateException ,并检查是否包含 FileNotFoundException异常。这真的是pretty可怕,但...你能不在身边这样的设计使得它的的需要被拦截?例如,开始检查该文件,并显示错误(或其他),如果当你发现它不存在。

If you really need a blocking one, you'll just have to call AsTask().Wait(), catch the AggregateException and check whether it contains a FileNotFoundException. It really is pretty horrible though... can you not design around this so that it doesn't need to be blocking? For example, start checking for the file, and show an error (or whatever) if and when you find it doesn't exist.

这篇关于使用异步方法无效里面等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆