【问题标题】:Getter property with async method doesn't finish executing具有异步方法的 Getter 属性未完成执行
【发布时间】:2015-08-18 20:30:41
【问题描述】:

问题:方法没有完成执行(没有例外,http 请求处于pending 状态)。

我必须实现下一个接口:

public interface IQueryableUserStore<TUser, in TKey> : IUserStore<TUser, TKey>, IDisposable where TUser : class, IUser<TKey>
{
    IQueryable<TUser> Users { get; }
}

我是这样做的:

public IQueryable<User> Users {
    get { return (this._userRepository.GetAll().Result).AsQueryable(); }
}

这里是GetAll() 的实现:

public async Task<IEnumerable<User>> GetAll() {
    const string query = @"
        select * from [dbo].[User]
    ";

    return (await this._db.QueryAsync<User>(query, new {}));
}

编辑:我从方法和方法调用中删除了异步行为,它可以工作。但是为什么它不能与异步一起使用呢?

这行得通:

public IQueryable<User> GetAll() {
    const string query = @"
        select * from [dbo].[User]
    ";

    return this._db.Query<User>(query, new {}).AsQueryable();
}

【问题讨论】:

  • 我认为您从get返回时也需要await
  • @Amit Kumar Ghosh,有GetAll().Result,应该提供await 行为,不是吗?
  • IQueryable&lt;T&gt;IEnumable&lt;T&gt;IEnumerable 直到你强制他们评估才会被评估。关于我的一个老问题的一些提示/解释:stackoverflow.com/questions/6677722/… -
  • @George Vovos,是的,看起来这不是连接问题,bcz 使用同步版本它就像一个魅力
  • 你可能陷入了僵局。在 asp.net 和 winforms 中使用 .Result 是不好的。见this

标签: c# asp.net .net asp.net-identity dapper


【解决方案1】:

Task.Result can easily cause deadlocks,正如我在博客中解释的那样。

您需要决定您希望您的数据库访问是同步的还是异步的。如果同步,则一路同步:

public IQueryable<User> GetAll() {
  const string query = @"
    select * from [dbo].[User]
  ";

  return this._db.Query<User>(query, new {}).AsQueryable();
}

如果异步,则一路异步:

public interface IQueryableUserStore<TUser, in TKey> : IUserStore<TUser, TKey>, IDisposable where TUser : class, IUser<TKey>
{
  Task<IQueryable<TUser>> GetUsers();
}

在绝大多数情况下,异步同步是一种反模式。 async all the way的原理我在一篇MSDN文章里讲了更多。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2013-01-27
  • 2023-04-08
  • 1970-01-01
  • 2014-08-03
  • 1970-01-01
  • 2020-04-02
  • 2016-08-04
  • 1970-01-01
相关资源
最近更新 更多