Using async await inside void method

强颜欢笑 提交于 2019-12-05 04:00:14

You can still make a void method async:

protected async void CannotChangeSignature()
{
    ...
}

Valid return types for an async method are:

  • 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.

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

EDIT: 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.

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