What is the best practice to update something multithreaded with EF? RRS feed

  • Question

  • I use EF within .NET Core, this is implemented inside Unit-Of-Work. The UOW is inserted into a class by Depency Injection. Within this class I call one function Run which loads 1000 records and executes another function for each record. This I do with the ActionBlock functionaliy and running 10 of them parallel. When I only edit the data I loaded outside the ActionBlock it all works fine. When starting loading data with the same UOW inside the thread I get message like

    - connetion already closed
    - reader still open

    What is the best practice to update something multithreaded with EF?

    Friday, May 25, 2018 2:49 PM

All replies

  • This is a example of the exception:

    System.InvalidOperationException: 'A second operation started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe.'

    This is a example of the code:

            private Data.Interfaces.IUnitOfWork _unitOfWork;

            public SynchronizePatch(Data.Interfaces.IUnitOfWork iUnitOfWork) {
                this._unitOfWork = iUnitOfWork;

            public void Run() {
                var tActionBlock = new ActionBlock<Data.Models.Base.Device>(
                    _ => this.RunDevice(_),
                    new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 10 }
                var tDevices = this._unitOfWork.Get<Data.Models.Base.Device>().Queryable().ToList();
                tDevices.ForEach(q => tActionBlock.Post(q));

            public void RunDevice(Data.Models.Base.Device iDevice) {
                var tPatches = this._unitOfWork.Get<Data.Models.Base.DevicePatch>().Queryable().Where(q => q.Device.Guid == iDevice.Guid).ToList();
                tPatches.ForEach(q => q.MaxFocusLastSync = DateTime.Now);

    Friday, May 25, 2018 3:19 PM
  • It is where you should post concerning EF issues.


    Friday, May 25, 2018 3:52 PM