-2

I made few of my existing methods asynchronous, now the in the properties from which I am calling those methods I see errors:

Cannot implicitly convert 'System.Threading.Tasks.Task<System.Collections.Generic.List<MyProj.BLL.Property>> TO 'System.Collections.Generic.List<MyProj.BLL.Property>>

public List<Property> UserProperties
{
    get
    {
        if (userProperties == null)
        {
           userProperties = GetUserProperties(UserId);
        }
    }
}

private async Task<List<Property>> GetUserProperties(int userId)
{
    var result = await UserDAL.GetUserProperties(userid);
    return result;
}
Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
claudia
  • 23
  • 1
  • 7

1 Answers1

4

'GetuserProperties' is an async methode which returns an (awaitable) Task. If you need the result of the calculations in that Task, there are two posibilities:

  1. Use userProperties = GetUserProperties(UserId).Result;.

This is pointless because Result is blocking your thread till the called Task returns its result. So in fact you make the call run synchronously. Furthermore there is a real possibility of a deadlock because an async method generally tries to return its result in the originating thread which is blocked waiting for the result.

  1. Use userProperties = await GetUserProperties(UserId).;. However, this is not allowed in a property setter (which cannot be async). See Await an async function from setter property

So, if you want to get the UserProperties asynchrounously you should abandon the property for that, make the 'GetUserProperties' method public and call that directly instead of using the property getter.

If you go that way, I would presume it would be best the make setting the UserProperties an async method as well and abandoning the property completely.

Johan Donne
  • 3,104
  • 14
  • 21
  • Hi Johan, In my case i cannot call GetUserProperties(UserId) directly because mine is an MVC view, and i can access only properties from the mvc view.. any other alternative ? – claudia Dec 06 '20 at 19:59
  • if you want to get the UserProperties synchrounously // do you mean asynchronously here because i want to run it asynchronously ? – claudia Dec 06 '20 at 20:03
  • @Claudia: that was a typo. I corrected it. – Johan Donne Dec 06 '20 at 20:35
  • @Claudia You could think of a mechanism where the UserProperties are fetched asynchrounously beforehand, then stored in a property, before having the View refresh itself (accessing the stored properties). – Johan Donne Dec 06 '20 at 20:38