記一次 ABP VNext 進程崩潰。錯誤源 System.ObjectDisposedException: Cannot access a disposed context instance.


正在做 excel 導入功能,代碼在自己的機器上正常運行,部署到 CentOS 后只要調用這塊代碼進程就直接崩掉,以下是問題代碼:

using (var stream = new MemoryStream())
{
     ImportQuestionsFile.CopyTo(stream);
     var dt = NPOIHelper.ImportExceltoDt(stream);
     var list = new List<CreateUpdateQuestionDto>();
     dt.AsEnumerable().ToList().ForEach(x =>
     {
        ...MORE CODE...
        list.Add(question);
     });
     _questionAppService.InsertManyAsync(list);
     return NoContent();
}

開始以為和以前一樣是進程占用內存太大導致,結果一頓排查進程不是被系統 kill 的。
Logs 里面又沒有日志,幸好使用了 Supervisor 守護進程,在它的日志里面找到的問題根源:

Unhandled exception. System.ObjectDisposedException: Cannot access a disposed context instance. A common cause of this error is disposing a context instance 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' on the context instance, or wrapping it in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
Object name: 'AssociationDbContext'.
   at Microsoft.EntityFrameworkCore.DbContext.CheckDisposed()
   at Microsoft.EntityFrameworkCore.DbContext.get_ContextServices()
   at Microsoft.EntityFrameworkCore.DbContext.get_ChangeTracker()
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.OnTracked(InternalEntityEntry internalEntityEntry, Boolean fromQuery)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.FireStateChanged(EntityState oldState)

根據日志分析發現是 DbContext 被 disposed 。最后排查是因為 _questionAppService.InsertManyAsync(list); 這個異步方法沒有加 await 程序就不會等待。但不知道為啥進程會崩潰。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM