【问题标题】:Async property in c#c#中的异步属性
【发布时间】:2020-05-08 02:31:46
【问题描述】:

在我的 Windows 8 应用程序中有一个 global 类,其中有一些静态属性,例如:

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配置正确,文件夹实际创建。)

【问题讨论】:

    标签: c# .net asynchronous async-await


    【解决方案1】:

    我建议你使用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;
    

    【讨论】:

      【解决方案2】:

      很好的解决方案: 不要做财产。创建一个异步方法。

      “我讨厌等待,我怎样才能让一切都同步?” 解决方案:How to call asynchronous method from synchronous method in C#?

      【讨论】:

      • 我希望同步获得任务的结果。只是想知道如何。
      • 不要对抗异步操作。它只会让你头疼。
      【解决方案3】:

      使用 await 关键字

       public async static StorageFolder GetAppRootFolder() 
       { 
                return await ApplicationData
                            .LocalFolder
                            .CreateFolderAsync("folderName");
       } 
      

      在你的代码中

      var myRootFolder = await StaticClass.GetAppRootFolder(); // this is a synchronous call as we are calling await immediately and will return the StorageFolder.
      

      【讨论】:

        【解决方案4】:

        这是一个想法。

        public Task<int> Prop {
            get
            {
                Func<Task<int>> f = async () => 
                { 
                    await Task.Delay(1000); return 0; 
                };
                return f();
            }
        }
        
        private async void Test() 
        {
            await this.Prop;
        }
        

        但它会为每次调用创建一个新的 Func 对象 这会做同样的事情

        public Task<int> Prop {
            get
            {
                return Task.Delay(1000).ContinueWith((task)=>0);
            }
        }
        

        您不能等待集合,因为不允许使用 await a.Prop = 1;

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-04-21
          • 2017-11-01
          • 2013-11-02
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多