Task.Factory.StarNew 和 ApplicationDbContext 更新

Task.Factory.StarNew and ApplicationDbContext Update

我需要在任务中更新我的 ApplicationDbContext 的 table;但是,我没有完成它。这是我收到的错误消息:

ex.Message = "Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose...

我知道这与我不太熟悉的线程有关。

代码如下:

  [HttpPost]
        public ActionResult WebHook([FromBody] BotRequest data)
        {

         Task.Factory.StartNew(() =>
                {

                //Read value from Table
                ContextWatsonFB contextWatsonFB = _context.ContextWatsonFB.Where(m => m.RecipientId == recipientid).FirstOrDefault();

                if (contextWatsonFB == null)
                {
                    contextWatsonFB = new ContextWatsonFB()
                    {
                        RecipientId = recipientid
                    };
                    _context.Add(contextWatsonFB);
                    _context.SaveChanges();

                }
                else
                {
                    if (!string.IsNullOrEmpty(contextWatsonFB.Context))
                    {
                        model = JsonConvert.DeserializeObject<Context>(contextWatsonFB.Context);
                    }

                }

                ///DO SOME STUFF ////////////////

                ///Here I need to update my table using some values processed above in "some stuff"

                ContextWatsonFB contextWatsonFB = _context.ContextWatsonFB.Where(m => m.RecipientId == recipientid).FirstOrDefault();

                contextWatsonFB.Context = JsonConvert.SerializeObject(context);
                _context.Update(contextWatsonFB);
                _context.SaveChanges();

                }
        }

如您所知,它是 Facebook 的 webhook 连接,需要在任务中处理该过程。在 "some stuff" 内,基本上我使用的是 IBM Watson Conversation 服务,它保留了一个我无法来回发送到 Facebook 的对话 "context",这就是为什么我想出将这些数据保留在a table 以保持来自 facebook messenger 的多个请求之间的差异。

幸运的是,下面的代码起到了作用:

        private readonly IServiceProvider _provider;

        public FacebookBotController(ApplicationDbContext context, IServiceProvider provider)
        {
            _provider = provider;

}

  [HttpPost]
        public ActionResult WebHook([FromBody] BotRequest data)
        {

            if (data == null || data?.entry?.Count == 0)
            {
                return new StatusCodeResult(StatusCodes.Status204NoContent);
            }


            try
            {

                var task = Task.Factory.StartNew(async () =>
                {

                    using (IServiceScope scope = _provider.GetRequiredService<IServiceScopeFactory>().CreateScope())
                    {
                        ApplicationDbContext _contx = _provider.GetService<ApplicationDbContext>();

                        ContextWatsonFB contextWatsonFB = await _contx.ContextWatsonFB.Where(m => m.SenderId == senderId).FirstOrDefaultAsync();

                        if (contextWatsonFB == null)
                        {
                            context = null;
                        }
                        else
                        {
                            context = JsonConvert.DeserializeObject<Context>(contextWatsonFB.Context);
                        }

                    }

}
}