Search code examples
c#xamlasynchronouswindows-8async-await

Using async await inside void method


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


Solution

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