gpt4 book ai didi

c# - 尝试将文件保存到 DbContext 时抛出 ObjectDisposedException

转载 作者:太空宇宙 更新时间:2023-11-03 22:36:05 24 4
gpt4 key购买 nike

我正在上传一个文本文件并将每条分割线写入数据库。该文件有超过一百万行。上传和保存到数据库有效,但在 await _context.SaveChangesAsync(); 行保存后中断并出现以下错误

System.ObjectDisposedException HResult=0x80131622 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() on the context, or wrapping the context 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: '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 仅适用于事件处理程序。它会触发一个即发即弃的任务,该任务无法等待或监视,并且在 ASP.NET 请求终止且其上下文被释放后仍可能运行很长时间。

不返回任何内容的异步方法的正确语法是async Task。方法签名应更改为

public async Task ImportUploadTextFile(string fileName)

调用 ImportUploadTextFile 的人都应该等待它。如果在 Controller 操作中调用它,则操作本身应该是异步的并等待它,例如:

public async Task Post(whatever)
{
....
await ImportUploadTextFile(fileName);
}

关于c# - 尝试将文件保存到 DbContext 时抛出 ObjectDisposedException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55143857/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com