【问题标题】:Cannot implicitly convert 'System.Threading.Tasks.Task<System.Collections.Generic.List> TO 'System.Collections.Generic.List<>无法将 'System.Threading.Tasks.Task<System.Collections.Generic.List> 隐式转换为 'System.Collections.Generic.List<>
【发布时间】:2020-12-06 19:05:15
【问题描述】:

我使一些现有方法异步,现在在我调用这些方法的属性中我看到错误:

不能隐式转换 'System.Threading.Tasks.Task> TO 'System.Collections.Generic.List>

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

【问题讨论】:

  • 你不是awaiting async 方法的结果。在这种情况下,您可能必须同步执行此操作,例如:通过使用任务的 .Result 属性
  • 以后请正确格式化代码。

标签: c# asynchronous async-await task


【解决方案1】:

'GetuserProperties' 是一个异步方法,它返回一个(等待的)任务。如果您需要该任务中的计算结果,有两种可能性:

  1. 使用 userProperties = GetUserProperties(UserId).Result;

这是没有意义的,因为 Result 会阻塞你的线程,直到被调用的 Task 返回它的结果。所以实际上你使调用同步运行。此外,确实存在死锁的可能性,因为异步方法通常会尝试在原始线程中返回其结果,该线程被阻塞等待结果。

  1. 使用 userProperties = await GetUserProperties(UserId).;。但是,这在属性设置器(不能是异步的)中是不允许的。见Await an async function from setter property

因此,如果您想异步获取 UserProperties,您应该为此放弃该属性,将“GetUserProperties”方法设为公开并直接调用该方法,而不是使用属性 getter。

如果你这样做,我认为最好将 UserProperties 设置为异步方法并完全放弃该属性。

【讨论】:

  • 嗨 Johan,在我的情况下,我不能直接调用 GetUserProperties(UserId),因为我的是 MVC 视图,我只能从 mvc 视图访问属性。还有其他选择吗?
  • 如果你想同步获取 UserProperties // 你的意思是异步这里是因为我想异步运行它吗?
  • @Claudia:这是一个错字。我更正了。
  • @Claudia 您可以考虑一种机制,其中 UserProperties 预先异步获取,然后存储在属性中,然后再让视图自行刷新(访问存储的属性)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-09
  • 2021-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多