问题
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