Using async await inside void method

杀马特。学长 韩版系。学妹 提交于 2019-12-06 21:09:26

问题


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

protected override void OnInitialize()

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

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.

So, the question is: How should I write this code using folder.OpenFileAsync method in Windows 8 API without changing signature of containing method


回答1:


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.



来源:https://stackoverflow.com/questions/11803370/using-async-await-inside-void-method

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