C# webapi 异步上下文问题

标签 c# entity-framework asynchronous asp.net-web-api

我有两个同时调用我的 webapi 的控制台应用程序,我在控制台应用程序中得到了来 self 的 api 的以下响应:

A second operation started on this context before a previous asynchronous operation completed. Use 'await' to ensure that any asynchronous operations have completed before calling another method on this context. Any instance members are not guaranteed to be thread safe.

因此他们同时调用我的 webapi,然后 webapi 内部的某些东西无法处理这 2 个异步调用,因此返回此错误。

我检查了我在 webapi 项目上的所有代码,所有方法都是异步的并等待,所以我不明白为什么我会得到这个。

这是 webapi 的代码。

Controller :

public class FederationsController : ApiController
{
    private readonly IFederationRepository _federationRepository;

    public FederationsController(IFederationRepository federationRepository)
    {
        _federationRepository = federationRepository;
    }

    [HttpGet]
    [Route("federations", Name = "GetFederations")]
    public async Task<IHttpActionResult> GetFederations()
    {
        var federations = await _federationRepository.GetAllAsync();
        return Ok(federations.ToModel());
    }
}

存储库

 public class FederationRepository : IFederationRepository, IDisposable
{
    private Models.DataAccessLayer.CompetitionContext _db = new CompetitionContext();

    #region IQueryable
    private IQueryable<Models.Entities.Federation> FederationWithEntities()
    {
        return _db.Federations.Include(x => x.Clubs)
                              .Where(x => !x.DeletedAt.HasValue && x.Clubs.Any(y => !y.DeletedAt.HasValue));
    }
    #endregion IQueryable

public async Task<IEnumerable<Models.Entities.Federation>> GetAllAsync()
    {
        return await FederationWithEntities().ToListAsync();
    }
}

映射器

public static class FederationMapper
{
    public static List<Federation> ToModel(this IEnumerable<Models.Entities.Federation> federations)
    {
        if (federations == null) return new List<Federation>();
        return federations.Select(federation => federation.ToModel()).ToList();
    }

    public static Federation ToModel(this Models.Entities.Federation federation)
    {
        return new Federation()
        {
            Name = federation.Name,
            FederationCode = federation.FederationCode,
            CreatedAt = federation.CreatedAt,
            UpdatedAt = federation.UpdatedAt
        };
    }
}

数据库上下文

public class CompetitionContext : DbContext
{
    public CompetitionContext() : base("ContextName")
    {
    }

    public DbSet<Federation> Federations { get; set; }
}

Unity配置

 public static class UnityConfig
{
    public static void RegisterComponents()
    {
        var container = new UnityContainer();
        container.RegisterType<IFederationRepository, FederationRepository>();
GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
}
}

感谢您的所有建议/帮助。

最佳答案

在您的存储库中,您正在创建一个 CompetitionContext 并重复使用它。我假设 IoC 设置将存储库注册为某种单一实例,因此每次都使用相同的存储库。如果是这种情况,您应该为每个方法调用创建一个新的 CompetitionContext。

另外,可能应该确保它是用 using 语句关闭的。

我也不清楚您的代码片段为什么要从 FederationWithEntities 方法返回 IQueryable,您是否有其他东西正在使用它?

无论如何,我可能会将 GetAllMethod 更改为如下所示:

public async Task<IEnumerable<Models.Entities.Federation>> GetAllAsync()
{
  using (Models.DataAccessLayer.CompetitionContext _db = new CompetitionContext())
  {
     return _db.Federations.Include(x => x.Clubs)
                           .Where(x => !x.DeletedAt.HasValue && x.Clubs.Any(y => !y.DeletedAt.HasValue))
                           .ToListAsync();
  }
}

关于C# webapi 异步上下文问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43300753/

相关文章:

c# - 如何在 C# 中将类型为 "IBuffer"的值读取为字符串?

performance - LINQ AsNoTracking 运行缓慢

java - 在 Java Swing 中为多线程应用程序创建可视化

c# - MySQL charset=UTF-8 with ConnectionReset=True 不工作

c# - 检测数据库条目的变化

javascript - 如何处理Node.js promise 链中的错误并解析 promise 数组

swift - swift 中的单元测试异步函数

javascript - CKeditor 的 KeyDown 事件

c# - Monotouch 的 Pinterest SDK 绑定(bind) - CreatePinWithImageURL 崩溃

c# - 从任务栏隐藏应用程序时未收到 PostMessage