DbContext per request aspboilerplate

左心房为你撑大大i 提交于 2021-01-28 14:20:48

问题


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.

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

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."

The question is how to create isolated DbContext inside this method. Please help me.


回答1:


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.

See the links

  • https://github.com/aspnetboilerplate/aspnetboilerplate/issues/619
  • Does Entity Framework support Multi-Threading?
  • Entity Framework and Multi threading

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



来源:https://stackoverflow.com/questions/47710541/dbcontext-per-request-aspboilerplate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!