Async property in C #

My Windows 8 application has a global class where there are several static properties, such as:

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

You can see that I want to use the application root folder somewhere else in the project, so I am making this a static property. Inside the recipient, I have to make sure that the root folder exists, otherwise create it. But CreateFolderAsync is an asynchronous method, here I need a synchronized operation. I tried GetResults() , but he InvalidOperationException . What is the correct implementation? (The .appmanifest package is configured correctly, the folder is actually created.)

+4
source share
4 answers

Good decision: Do not make real estate. Make an asynchronous method.

"Hey guys, I hate waiting, how can I do everything in sync?" Solution: How to call an asynchronous method from a synchronous method in C #?

+7
source

I suggest you use asynchronous lazy initialization .

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

You can directly await :

 var rootFolder = await EnvironmentEx.AppRootFolder; 
+12
source

use the wait keyword

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

and in your code

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

Here is an idea.

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

but it creates a new func object for each call it will do the same

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

You cannot wait for dialing because await a.Prop = 1; is not allowed

0
source

Source: https://habr.com/ru/post/1433739/


All Articles