漂流瓶做任务网站,软件商店app,企业为什么要验资,重庆提供行业网站建站报价背景最近做了个项目有个接口涉及到批量计算的问题#xff0c;耗时比较长。大家都知道#xff0c;接口等待时间太长肯定是不可取的。那么只能做异步处理了#xff1b;但是问题来了这个项目没有什么消息队列、redis之类的使用#xff0c;本着怎么简单怎么来的思路#xff0c…背景最近做了个项目有个接口涉及到批量计算的问题耗时比较长。大家都知道接口等待时间太长肯定是不可取的。那么只能做异步处理了但是问题来了这个项目没有什么消息队列、redis之类的使用本着怎么简单怎么来的思路新搞个消息队列不现实这时候多线程派上用场。再次遇到问题于是噼里啪啦写了一顿发现有个问题我的方法涉及到很多ef core 数据库操作在多线程的条件下报错如下:System.InvalidOperationException: A second operation was started on this context instance before a previous operation completed. This is usually caused by different threads concurrently using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid2097913生命周期为Scope方式随着请求的结束实例生命周期也会被释放因此在多线程下若共享实例容易出现实例已释放的错误报错如下Instances cannot be resolved and nested lifetimes cannot be created from this LifetimeScope as it (or one of its parent scopes) has already been disposed.Autofac at Autofac.Core.Lifetime.LifetimeScope.BeginLifetimeScope(Object tag)。通过注入IServiceProvider就是这种方式也是不行的还是需要改到原来的代码还是违背初衷。峰回路转本来一筹莫展的突然想到既然接口一次太慢了那就分2次执行第二次可以使用多线程触发自己调用自己的耗时接口这样就不需要改到原来的底层逻辑要做的仅仅是把自己的方法拆分成2个。1、请求一个异步方法然后接口直接返回/// summary/// 批量 添加 一级指标 数据74.22分全省第10名/// /summary/// param nameentity/param/// returns/returns[HttpPost][Route(adminaddAreadatabatch)]public bool addAreadatabatch(ListAreadataDto entity){// foreach (var item in entity ?? new ListAreadataDto())// {// try// {_chartBll.Addbat(entity);// }// catch (Exception ex)// {// _logger.Error(ex);// }// }
ThreadPool.QueueUserWorkItem(new WaitCallback(InsertNewsInfoExt), JsonConvert.SerializeObject(entity));return true;}2、这里做一个http请求private void InsertNewsInfoExt(object info){var client new RestClient(http://xxxx/api/ningdeChart/updateAreadata);client.Timeout -1;var request new RestRequest(Method.POST);request.AddHeader(Content-Type, application/json);var body info.ToString();request.AddParameter(application/json, body, ParameterType.RequestBody);IRestResponse response client.Execute(request);Console.WriteLine(response.Content);}3、在原来的接口adminaddAreadatabatch做下二次拆分提供一个新的api[HttpPost][Route(updateAreadata)]public bool updateAreadata(ListAreadataDto entity){foreach (var item in entity ?? new ListAreadataDto()){try{_logger.Info(updateAreadata);_chartBll.updateAreadata(item.areaid, item.t1);}catch (Exception ex){_logger.Error(ex);}}return true;}问题得到解决。