在C#Async属性 [英] Async property in c#

查看:603
本文介绍了在C#Async属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Windows 8应用程序存在的全球的类,其中有像几个静态的属性:

In my windows 8 application there is a global class where there are a few static properties like:

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();
         }
     }
}

您可以看到我想要在项目中的其他地方使用该应用程序的根文件夹,所以我让一个静态属性。吸气里面,我需要确保根文件夹存在,否则创建它。但 CreateFolderAsync 是一个异步方法,在这里我需要一个同步操作。我试图 GetResults(),但它抛出一个出现InvalidOperationException 。什么是正确的实现? (实际上是创建该文件夹的package.appmanifest配置正确。)

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.)

推荐答案

很好的解决:
不要让一个属性。做一个异步方法。

Good solution: Don't make a property. Make an async method.

嘿,伙计们,我讨厌等待,我怎样才能使一切synchrnous?解决方案:
<一href=\"http://stackoverflow.com/questions/9343594/how-to-call-asynchronous-method-from-synchronous-method-in-c\">How从同步方法调用异步方法在C#中?

这篇关于在C#Async属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆