Async property in c#

后端 未结 4 1499
礼貌的吻别
礼貌的吻别 2020-12-17 01:14

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

public class EnvironmentEx
{
     public static Us         


        
相关标签:
4条回答
  • 2020-12-17 01:34

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

    "I hate await, how can I make everything synchronous?" solution: How to call asynchronous method from synchronous method in C#?

    0 讨论(0)
  • 2020-12-17 01:40

    use the await 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.
    
    0 讨论(0)
  • 2020-12-17 01:40

    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 every call this would do the same

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

    You can't await a set since await a.Prop = 1; is not allowed

    0 讨论(0)
  • 2020-12-17 01:54

    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 then await it directly:

    var rootFolder = await EnvironmentEx.AppRootFolder;
    
    0 讨论(0)
提交回复
热议问题