c# - C# 中的异步属性

标签 c# .net asynchronous async-await

在我的 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/

相关文章:

c# - [DatabaseGenerated(DatabaseGenerationOption.Computed)] 数据注释有什么作用?

c# - Xml.Linq : Descendants() returns nothing

c# - RichTextBox 选择突出显示

.net - 我如何指定主题默认字体的粗体版本?

database - Redis//Benchmark工具//如何开启异步测试

javascript - Redis Javascript 异步函数

c# - ASP.NET JavaScript 函数的用户控制范围

c# - 带有自定义项模板文本的 wpf 组合框

c# - 'method' 匹配委托(delegate) 'RoutedEventHandler' 没有重载

asynchronous - 为什么异步编程更快