In my windows 8 application there is a global class where there are a few static properties like:
publicclassEnvironmentEx{publicstaticUserCurrentUser{get;set;}//and some other static properties//notice this onepublicstaticStorageFolderAppRootFolder{get{returnKnownFolders.DocumentsLibrary.CreateFolderAsync("theApp",CreationCollisionOption.OpenIfExists).GetResults();}}}
You can see I want to use the application root folder somewhere else in the project, so I make it a static property. Inside the getter, I need to make sure the root folder exists,otherwise create it. But the CreateFolderAsync is an async method, here I need a synchronized operation. I tried GetResults() but it throws an InvalidOperationException. What is the correct implementation? (The package.appmanifest is correctly configured, the folder is actually created.)
回答1:
Good solution: Don't make a property. Make an async method.
var rootFolder = await EnvironmentEx.AppRootFolder;
回答3:
use the await keyword
public async staticStorageFolderGetAppRootFolder(){return await ApplicationData.LocalFolder.CreateFolderAsync("folderName");}
and in your code
var myRootFolder = await StaticClass.GetAppRootFolder();// this is a synchronous call as we are calling await immediately and will return the StorageFolder.