Ed *_*dau 2 c# multithreading entity-framework
我正在编写一个针对Entity Framework 6.1.3的C#.NET4.5控制台应用程序.我使用的工作单元范例如下:
public class UnitOfWork : IUnitOfWork, IDisposable
{
private readonly DataContext _context;
private readonly List<object> _repositories = new List<object>();
public UnitOfWork(DataContext context)
{
_context = context;
_context.Configuration.LazyLoadingEnabled = false;
}
public IRepository<T> GetRepository<T>() where T : class
{
//try to get existing repository
var repo = (IRepository<T>)_repositories.SingleOrDefault(r => r is IRepository<T>);
if (repo == null)
{
//if not found, create it and add to list
_repositories.Add(repo = new EntityRepository<T>(_context));
}
return repo;
}
public int Commit()
{
return _context.SaveChanges();
}
public bool AutoDetectChanges
{
get { return _context.Configuration.AutoDetectChangesEnabled; }
set { _context.Configuration.AutoDetectChangesEnabled = value; }
}
Run Code Online (Sandbox Code Playgroud)
我的存储库是这样的:
public class EntityRepository<T> : IRepository<T> where T: class
{
protected readonly DbContext Context;
protected readonly DbSet<T> DbSet;
public EntityRepository(DbContext context)
{
Context = context;
DbSet = Context.Set<T>();
}
public IQueryable<T> All()
{
return DbSet;
}
….. other functions….
public virtual void Add(T entity)
{
DbEntityEntry dbEntityEntry = Context.Entry(entity);
if (dbEntityEntry.State != EntityState.Detached)
{
dbEntityEntry.State = EntityState.Added;
}
else
{
DbSet.Add(entity);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我称之为:
var rep = _uow.GetRepository<TableOfPies>();
rep.Add(Pie);
_uow.Commit();
Run Code Online (Sandbox Code Playgroud)
我的控制台应用程序有多个线程,每个线程都希望在我的基于云的SQL Server数据库中更新/编辑/添加到相同的表.
我已经使用锁为我的其他代码实现了线程安全的代码,但我不知道如何让Entity线程安全?现在,我收到以下错误:
INNER EXCEPTION: New transaction is not allowed because there are other threads running in the session.
我已经在线查看,但未能找到很多关于实体和多线程的信息.我听说Entity不支持多线程应用程序但发现听到相信.任何指针都将非常感激.
DataContext的文档说明:
任何实例成员都不保证是线程安全的.
这也是我所经历的.我已经尝试做你正在做的事情,并且我已经看到了奇怪的错误,它们备份了它不是线程安全的想法.
您必须在每个线程中创建一个新的DataContext实例.
| 归档时间: |
|
| 查看次数: |
4553 次 |
| 最近记录: |