简体   繁体   English

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

[英]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.

相关问题 尝试上传文件时出现ObjectDisposedException - ObjectDisposedException when trying to upload a file 尝试保存Emitted程序集时抛出NotSupportedException - NotSupportedException is thrown when trying to save Emitted assembly EF Core DbContext ObjectDisposedException - EF Core DbContext ObjectDisposedException 表单引发的ObjectDisposedException - ObjectDisposedException thrown by form 尝试列出对象时出现System.ObjectDisposedException - System.ObjectDisposedException when trying to list an object 尝试从SQLiteDataReader读取时遇到ObjectDisposedException - Encountering ObjectDisposedException when trying to read from SQLiteDataReader System.ObjectDisposedException 尝试访问 DataContext 时 - System.ObjectDisposedException when trying to access DataContext 尝试从List接收数据时System.ObjectDisposedException - System.ObjectDisposedException when trying to receive the data from a List 尝试传递 id 时出现 ASP.NET MVC ObjectDisposedException - ASP.NET MVC ObjectDisposedException when trying to pass id 尝试使用dbcontext将数据保存到数据库时出错。 不是float类型的有效实例 - Error when trying to save data to a database with dbcontext. Not a valid instance of type float
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM