'无法访问已处置的对象。导致此错误的常见原因是处置从依赖项注入解析的上下文

Ekr*_*rem 3 c# model-view-controller threadpool asp.net-core

我正在使用ThreadPool通用存储库,但收到此错误;

'无法访问已处置的对象。导致此错误的一个常见原因是处置从依赖项注入解析的上下文,然后尝试在应用程序的其他位置使用相同的上下文实例。如果您在上下文上调用 Dispose() 或将上下文包装在 using 语句中,则可能会发生这种情况。如果您使用依赖项注入,则应该让依赖项注入容器负责处理上下文实例。

private readonly AuthorizedServiceService _authorizedServiceService;
        private readonly CustomerService _customerService;
        public IConfigurationRoot Configuration { get; }

        public UpdateService(AuthorizedServiceService authorizedServiceService, CustomerService customerService)
        {
            _authorizedServiceService = authorizedServiceService;
            _customerService = customerService;
        }


        public void UpdateAllRecords()
        {

            _authorizedServiceService.GetByActive().ToList().ForEach(UpdateAuthorizedServiceRecords);
        }

        void UpdateAuthorizedServiceRecords(AuthorizedService authorizedService)
        {
            //UpdateStart(authorizedService);
            var mywatch = new Stopwatch();

            mywatch.Start();

            ThreadPool.QueueUserWorkItem(new WaitCallback(state => { UpdateStart(authorizedService); }));

            mywatch.Stop();
            mywatch.Reset();
        }


        public void UpdateStart(AuthorizedService authorizedService)
        {
            UpdateCustomers(authorizedService);
            ThreadPool.QueueUserWorkItem(new WaitCallback(state => { UpdateCustomers(authorizedService); }));

        }

        internal void UpdateCustomers(AuthorizedService authorizedService)
        {
            try
            {
                if (authorizedService.CustomerUpdateLocked)
                    return;

                var carDatabaseClient = new DataCarDatabaseClient();
                var result = carDatabaseClient.GetCustomers(authorizedService, authorizedService.LastCustomerUpdate);

                var dataRows = Convert<Customer>(result).Select(s=>
                {
                    s.Id = authorizedService.Code + "-" + s.DcId;
                    s.AuthorizedService = authorizedService;
                    return s;
                }).ToList();

                _customerService.SaveOrUpdate(dataRows.OrderBy(p=>p.Id).FirstOrDefault(),p=> p.Id != null);

            }
            catch (Exception e)
            {
                // ignored
            }
        }
Run Code Online (Sandbox Code Playgroud)

通用存储库方法;

public void AddOrUpdate(T entity, Expression<Func<T, bool>> predicate)
{
    var exists = predicate != null ? Context.Set<T>().Any(predicate) : Context.Set<T>().Any();
    if (!exists)
        Context.Set<T>().Add(entity);
    else
        Context.Set<T>().Update(entity);

    Context.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*bov 9

发生这种情况是因为主线程中的所有依赖项在执行完成后都被释放,并且您尝试在另一个线程中访问它们。要处理这种情况,您需要在后台线程中创建一个范围并AuthorizedServiceService在那里解决:

private readonly IServiceScopeFactory _scopeFactory;

public UpdateService(AuthorizedServiceService authorizedServiceService, CustomerService customerService, IServiceScopeFactory scopeFactory)
{
    _authorizedServiceService = authorizedServiceService;
    _customerService = customerService;
    _scopeFactory = scopeFactory;
}

public void UpdateStart(AuthorizedService authorizedService)
{    
    ThreadPool.QueueUserWorkItem(new WaitCallback(state => { 
    using (scope = _scopeFactory.CreateScope())
    {
        var scopedAuthorizedService = scope.ServiceProvider.GetService(typeof(AuthorizedServiceService));
        UpdateCustomers(scopedAuthorizedService); }));
    }
 }
Run Code Online (Sandbox Code Playgroud)