[英]ObjectDisposedException thrown when trying to save files to a DbContext
I am uploading a text file and writing each split line to a database. 我正在上传文本文件并将每个分割线写入数据库。 The file has over a million lines.
该文件有超过一百万行。 The upload and saving to the database works but breaks after the save on the
await _context.SaveChangesAsync();
上传和保存到数据库工作但在保存
await _context.SaveChangesAsync();
后中断await _context.SaveChangesAsync();
line with the following error 出现以下错误
System.ObjectDisposedException HResult=0x80131622 Message=Cannot access a disposed object.
System.ObjectDisposedException HResult = 0x80131622 Message =无法访问已处置的对象。 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() on the context, or wrapping the context in a using statement.
如果您在上下文中调用Dispose()或将上下文包装在using语句中,则可能会发生这种情况。 If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
如果使用依赖项注入,则应该让依赖项注入容器负责处理上下文实例。 Object name: 'LanternDBContext'.
对象名称:'LanternDBContext'。
public async void ImportUploadTextFile(string fileName)
{
string rootFolder = _hostingEnvironment.WebRootPath;
using (StreamReader sr = new StreamReader(Path.Combine(rootFolder + "/UploadedFiles/", fileName)))
{
List<UploadTextFile> InputList = new List<UploadTextFile>();
while (sr.Peek() >= 0)
{
string str;
string[] strArray;
str = sr.ReadLine();
strArray = str.Split(' ');
InputList.Add(new UploadTextFile
{
CorpCode = strArray[0],
AccountCode = strArray[1],
CostCenter = strArray[2]
});
}
_context.UploadTextFile.AddRange(InputList);
}
await _context.SaveChangesAsync();
}
async void
is only meant for event handlers . async void
仅适用于事件处理程序 。 It fires off a fire-and-forget task that can't be awaited or monitored and could still be running long after an ASP.NET request terminates and its context gets disposed. 它会触发一个无法等待或监视的即发即弃任务,并且在ASP.NET请求终止并且其上下文被释放后,它仍然可以运行很长时间。
The proper syntax for an asynchronous method that doesn't return anythig is async Task
. 不返回anythig的异步方法的正确语法是
async Task
。 The method signature should change to 方法签名应更改为
public async Task ImportUploadTextFile(string fileName)
and whoever calls ImportUploadTextFile
should await it. 而且任何调用
ImportUploadTextFile
都应该等待它。 If it's called in a controller action, the action itself should be asynchronous and await it, eg : 如果在控制器动作中调用它,则动作本身应该是异步的并等待它,例如:
public async Task Post(whatever)
{
....
await ImportUploadTextFile(fileName);
}
Your db context is disposed by the time you trying to save changes. 尝试保存更改时,将丢弃您的数据库上下文。 Probably your method
可能是你的方法
ImportUploadTextFile
ImportUploadTextFile
is used out of the proper scope. 使用超出适当的范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.