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
You can still make a
voidmethod async:Valid return types for an async method are:
voidTaskTask<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>:EDIT: If you really need a blocking one, you’ll just have to call
AsTask().Wait(), catch theAggregateExceptionand check whether it contains aFileNotFoundException. 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.