简体   繁体   中英

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

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;
}

'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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM