Tulika
Tulika

Reputation: 685

Await an async function from setter property

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.

Upvotes: 8

Views: 14479

Answers (3)

Zanyar Jalal
Zanyar Jalal

Reputation: 1874

You can't use async function with property

Alternative Can use Result Property

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

Upvotes: -1

hubot
hubot

Reputation: 391

Use

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

[EDIT]

Upvotes: -2

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239646

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.

Upvotes: 15

Related Questions