在我的 Windows 8 应用程序中有一个全局类,其中有一些静态属性,例如:
public class EnvironmentEx
{
public static User CurrentUser { get; set; }
//and some other static properties
//notice this one
public static StorageFolder AppRootFolder
{
get
{
return KnownFolders.DocumentsLibrary
.CreateFolderAsync("theApp", CreationCollisionOption.OpenIfExists)
.GetResults();
}
}
}
您可以看到我想在项目的其他地方使用应用程序根文件夹,所以我将其设为静态属性。在 getter 内部,我需要确保根文件夹存在,否则创建它。但是 CreateFolderAsync
是一个异步方法,这里我需要一个同步操作。我尝试了 GetResults()
,但它抛出了 InvalidOperationException
。什么是正确的实现? (正确配置了 package.appmanifest,实际创建了文件夹。)
最佳答案
我建议你使用 asynchronous lazy initialization .
public static readonly AsyncLazy<StorageFolder> AppRootFolder =
new AsyncLazy<StorageFolder>(() =>
{
return KnownFolders.DocumentsLibrary
.CreateFolderAsync("theApp", CreationCollisionOption.OpenIfExists)
.AsTask();
});
然后你可以直接await
它:
var rootFolder = await EnvironmentEx.AppRootFolder;
关于c# - C# 中的异步属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12384309/