Cannot access a disposed object in ASP.NET Core


Cannot access a disposed object in ASP.NET Core

楠木大叔????

导航

  • 常见原因
  • 总结

??对于.neter来说,在使用ASP.NET Core的过程中,大家或多或少会遇到这样的报错——“Cannot access a disposed object”。出现这样的异常的原因有很多,如果它在调试的时候出现是很容易解决的,但是有些时候它在本地运行良好,等到你部署到生产环境才会表现出来。针对这个异常,请跟随我一起来分析和探究其根本原因。

??在ASP.NET Core开发中,我多次碰见了这样的报错,并且跟踪这个bug很艰难。这样的报错有多种原因。有时仅凭其表现的“症状”就能修复这个Bug,但是有时候又极其痛苦。通过寻找“病因”,我们可以反过来优化自己的代码。

??错误信息很清楚:

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: ‘XXXContext‘.

常见原因

对象已经释放(The object is disposed in your code)

??最简单的原因是你有一个可以释放的对象,然后你在代码的某个地方释放了它。也可能是你释放了一个使用了该对象的对象。当你试图访问一个被释放的对象时,就引发了该异常。此时,你要做的就是查看该范围的代码路径,或者上下文调用关系,通过打断点来排查该问题。

代码异步执行(Some code is running async)

??我遇到的另外一种原因是你在新线程中执行了某段逻辑。依赖的框架释放了对象,并将该对象返回给主线程。
新的线程执行了已经释放的对象,然后引发异常。要解决此问题.你必须单独地开启新线程来管理这个可以被释放的对象。

Task.Run( () => { // or ThreadPool.QueueUserWorkItem(async _ => {
    using (var context = **create your new context here, handle it directly or let the DI framework do its magic**){
        foreach(var user in Users){
            email.Send(user.email);
            context.....;
            context.SaveChanges();
        }
    }
});

??在APS.NET Core Web API 中,我们可以用Swashbuckle.AspNetCoreNSwag这两个包来实现Swagger,而且二者都是github上开源的。此外,nswag还提供了生成typescript客户端代码的方法以及用于API的服务代码。

使用async void 而非 async Task

??另一种原因可能是你在本应该使用使用async Task的地方使用了async void。潜在的异步代码会在你的线程返回之后执行。就像在代码中启动一个新线程一样,它可能会意外地正确运行。在这种情况下,您可能只在release版本中看到错误。当您不知道在哪里查找时,这可能很难调试。PS:笔者恰好遭遇该情况,我和我的小伙伴花费了一天时间来找这个bug。

?? 错误的写法:

public async void FailtyMethod(){

?? 正确的写法:


public async Task CorrectMethod(){

总结

??解决这些bug,有时候会令人沮丧,甚至抓狂。我曾今和我的另外两个小伙伴花费了一天时间来找这个bug。最后大家都黔驴技穷。

??我希望这篇文章能够帮助到你。

参考

关注
??请关注微信公众号智客坊

原文地址:https://www.cnblogs.com/lucky_hu/p/11667957.html

时间: 2024-11-08 22:24:57

Cannot access a disposed object in ASP.NET Core的相关文章

asp.net Core HttpClient 出现Cannot access a disposed object. Object name: 'SocketsHttpHandler' 的问题。

ASP.NET Core 部署在Centos 中 偶尔出现 One or more errors occurred. (Cannot access a disposed object.Object name: 'SocketsHttpHandler'.) 之前的写法如下: var httpclientHandler = new HttpClientHandler(); httpclientHandler.ServerCertificateCustomValidationCallback = (m

Xamarin.Forms bug? System.ObjectDisposedException: Cannot access a disposed object

Hi, My Android Xamarin.Forms application uses a Navigation stack to display various views, I often have a list on a screen (A) that once a cell is clicked I push onto the stack a new screen (B), the user completes some form fields and then clicks a b

System.Net.Sockets.Socket SendAsync System.ObjectDisposedException: Cannot access a disposed object.

发生未处理的域异常! System.ObjectDisposedException: Cannot access a disposed object. Object name: 'System.Net.Sockets.Socket'. at System.Net.Sockets.Socket.SendAsync(SocketAsyncEventArgs e) 在进行Socket长连接时,若服务器或客户端出现异常时,另外一端对Socket对话进行操作时,程序会出现无法访问已释放的对象的问题.例如客

Cannot access a disposed object. A common cause of this error is disposing

异常信息: An unhandled exception was thrown by the application.System.ObjectDisposedException: 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 t

ASP.NET Core 新建线程中使用依赖注入的问题

问题来自博问的一个提问 .net core 多线程数据保存的时候DbContext被释放 . TCPService 通过构造函数注入了 ContentService , ContentService 的实例依赖了 AppDbContext (继承自 EF Core 的 DbContext).在 TCPService 中通过 Thread.Start 启动了一个新的线程执行了 TCPService 中的 Receive 方法,在 Receive 方法中通过 ContentService 进行保存数

Access forbidden! You don't have permission to access the requested object. It is either read-protected or not readable by the server

好久不没弄 apache和php了,突然遇到这种奇葩的问题,本来想直接在网上找现成的解决思路,结果网上搜索花了不少功夫,也没找到原因. 后来看日志文件:apache\logs\error.log发现了蛛丝马迹. [core:error] [pid 200:tid 1704] (20024)The given path is misformatted or contained invalid characters: [client 127.0.0.1:51040] AH00127: Cannot

mac上的xampp出现Access forbidden! You don’t have permission to access the requested object. It is either

一个Joomla!程序,之前是在win上的xampp上运行得非常好的,当我把它拿到mac下面的xampp上去运行的时候,发现有问题,没法运行,报以下的错误: Access forbidden!  You don't have permission to access the requested object. It is either read-protected or not readable by the server. 这时可以找到apache的httpd.conf文件,找出<Direct

Dependency injection in ASP.NET Core

原文 ASP.NET Core supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies. For more information specific to dependency injection within MVC con

Professional C# 6 and .NET Core 1.0 - 40 ASP.NET Core

本文内容为转载,重新排版以供学习研究.如有侵权,请联系作者删除. 转载请注明本文出处:Professional C# 6 and .NET Core 1.0 - 40 ASP.NET Core ----------------------------------------------------------------------- What's In This Chapter? Understanding ASP.NET Core 1.0 and Web Technologies Using