Await an async function from setter property

£可爱£侵袭症+ 提交于 2021-01-02 07:08:45

问题


I need to await to an async function from a property setter method.

public String testFunc()
{
get
{

}
set
{
    //Await Call to the async func <asyncFunc()>

}
}

I understand we should not make async properties, so what is the optimal way to do this.


回答1:


You can't make async properties and you shouldn't want to - properties imply fast, non blocking operations. If you need to perform a long running activity, as implied by you're wanting to kick of an async operation and wait for it, don't make it a property at all.

Remove the setter and make a method instead.




回答2:


Use

public bool SomeMethod
{
  get { /* some code */ }
  set
  {
    AsyncMethod().Wait();
  }
}
public async Task AsyncMethod() {}

[EDIT]




回答3:


You can't use async function with property

Alternative Can use Result Property

public string UserInfo
{
    get => GetItemAsync().Result;
}


来源:https://stackoverflow.com/questions/34650013/await-an-async-function-from-setter-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!