c#中的异步属性

Che*_*hen 5 .net c# 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();
         }
     }
}
Run Code Online (Sandbox Code Playgroud)

您可以看到我想在项目的其他位置使用应用程序根文件夹,因此我将其设置为静态属性.在getter中,我需要确保根文件夹存在,否则创建它.但这CreateFolderAsync是一个异步方法,这里我需要一个同步操作.我试过了,GetResults()但它抛出一个InvalidOperationException.什么是正确的实施?(package.appmanifest已正确配置,实际创建了该文件夹.)

Ste*_*ary 15

我建议你使用异步延迟初始化.

public static readonly AsyncLazy<StorageFolder> AppRootFolder =
    new AsyncLazy<StorageFolder>(() =>
    {
      return KnownFolders.DocumentsLibrary                    
          .CreateFolderAsync("theApp", CreationCollisionOption.OpenIfExists)
          .AsTask();
    });
Run Code Online (Sandbox Code Playgroud)

你可以await直接:

var rootFolder = await EnvironmentEx.AppRootFolder;
Run Code Online (Sandbox Code Playgroud)


Eup*_*ric 11

好的解决方案: 不要做财产.制作异步方法.

"嘿伙计们,我讨厌等待,我怎么能让一切变得同步?" 解决方案: 如何从C#中的同步方法调用异步方法?

  • 不要反对异步操作.它只会让你头疼. (4认同)