c#中的异步属性
在我的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已正确配置,实际创建了该文件夹。)
好的解决方案:不要做财产。 制作异步方法。
“嘿伙计们,我讨厌等待,我怎么能让一切都变得同步?” 解决方案: 如何从C#中的同步方法调用异步方法?
我建议你使用异步延迟初始化 。
public static readonly AsyncLazy AppRootFolder = new AsyncLazy (() => { return KnownFolders.DocumentsLibrary .CreateFolderAsync("theApp", CreationCollisionOption.OpenIfExists) .AsTask(); });
然后你可以直接await
它:
var rootFolder = await EnvironmentEx.AppRootFolder;
使用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.
这是一个想法。
public Task Prop { get { Func> f = async () => { await Task.Delay(1000); return 0; }; return f(); } } private async void Test() { await this.Prop; }
但它会为每次调用创建一个新的Func对象
public Task Prop { get { return Task.Delay(1000).ContinueWith((task)=>0); } }
await a.Prop = 1;
您无法等待集合await a.Prop = 1;
不被允许