每个请求的dbContext aspboilerplate [英] DbContext per request aspboilerplate
问题描述
我需要为导入文件实现多线程后台作业.我已经用后台作业(Hangfire)实现了它.但是,如果我使用一个线程,它将非常慢.函数看起来像这样.
I need to implement multithreading background job for import file. I have implemented it with background job(Hangfire). But if i use one thread it goes very slow. The function look like this.
我使用非事务处理单元将更改立即保存到db.
I using non-transaction unit to save changes to db immediately.
var contactFound = await _contactRepository.FirstOrDefaultAsync(x => x.Email.ToLower() == contact.Email.ToLower());
if (contactFound != null)
{
await _bjInfoManager.AddLog(args.JobId, "Found duplicated email: " + contact.Email);
}
else
{
contact.ContactListId = args.ContactListId;
contact.Email = contact.Email.ToLower();
await _contactRepository.InsertAsync(contact);
//Save changes in db
await CurrentUnitOfWork.SaveChangesAsync();
}
当我尝试将其与Producer-Consumer Dataflow Pattern结合使用时,会出现问题.我抛出异常在先前的异步操作完成之前,在此上下文上启动了第二个操作."
The problem occur when I tries to use this with Producer-Consumer Dataflow Pattern. I throws the exception "A second operation started on this context before a previous asynchronous operation completed."
问题是如何在此方法内创建隔离的DbContext.请帮助我.
The question is how to create isolated DbContext inside this method. Please help me.
推荐答案
事务不应该是多线程的.如果您在UOW中创建新的任务/线程,则可以在using块中使用IUnitOfWork.Begin(TransactionScopeOption.RequiresNew)创建单独的UOW.
Transactions should not be multi-threaded. If you create a new task/thread in a UOW, you can create a seperated UOW using IUnitOfWork.Begin(TransactionScopeOption.RequiresNew) in a using block.
查看链接
如果使用的是Microsoft SQL Server,则建议您使用批量插入.它比实体框架超级快.
If you are using Microsoft SQL Server, then I recommend you to use bulk insert. It's super fast than entity framework.
https://docs.microsoft.com/en-us/sql/t-sql/statements/bulk-insert-transact-sql
这篇关于每个请求的dbContext aspboilerplate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!