8

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.

Tulika
  • 625
  • 1
  • 8
  • 23
  • Show this post, i think this is your solution http://stackoverflow.com/questions/6602244/how-to-call-an-async-method-from-a-getter-or-setter – rdn87 Jan 07 '16 at 08:06
  • Possible duplicate of [How to call an async method from a getter or setter?](https://stackoverflow.com/questions/6602244/how-to-call-an-async-method-from-a-getter-or-setter) – Michael Freidgeim Dec 10 '17 at 05:24

3 Answers3

13

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.

Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448
  • +1 more straight to the point. It is not supported in C#. Only methods, lambda expressions or anonymous methods can `await` – Leo Jan 07 '16 at 08:08
  • I completely agree with the point you're making. But isn't it still possible to use `Task.Wait()` in a property getter/setter? – Domysee Jan 07 '16 at 08:14
  • 1
    @Domysee - possible, yes. Advisable, no. – Damien_The_Unbeliever Jan 07 '16 at 08:14
  • 7
    @Damien_The_Unbeliever generally I agree with what you say about setters, but as usual, any general rule has exceptions. In this case, the MVVM pattern often requires doing async operations from setters since changing a property value of a VM object should be regarded as en Event. Getting around that often results in headaches, bugs and/or messy code when working with WPF. – Yuval Perelman Dec 11 '19 at 13:56
  • 3
    Any solution for when you have a databound setter, such as a filter field and you want to kickoff loading data into a collection async? – Arrow_Raider May 11 '20 at 20:55
  • 1
    @Damien_The_Unbeliever I have a wpf application where ActualPageNumber property is used with databinding. So when I change the property, the setter should access the db which can be slow. That is why I wanted an async setter, to keep the gui responsive. – Istvan Heckl Oct 02 '20 at 13:52
-1

Use

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

[EDIT]

Ghasem
  • 14,455
  • 21
  • 138
  • 171
hubot
  • 393
  • 5
  • 18
-1

You can't use async function with property

Alternative Can use Result Property

public string UserInfo
{
    get => GetItemAsync().Result;
}
Zanyar Jalal
  • 1,407
  • 12
  • 29