简体   繁体   English

如何正确处理没有IDisposable的对象

[英]How to Properly dispose an object without IDisposable

In my ASP.NET MVC app I have a controller like this: 在我的ASP.NET MVC应用程序中,我有一个像这样的控制器:

[HttpPost]
public ActionResult CreateTestCategory(TestCategory testCategory)
{
    BLL.Admin.CreateTestCategory obj = new BLL.Admin.CreateTestCategory();
    obj.Create(testCategory.TestCategoryName);
    //((IDisposable)obj).Dispose();

    return RedirectToAction("TestCategory", "Admin");
}  

Here the BLL.Admin.CreateTestCategory is in another layer and it does not implement IDisposable. 这里的BLL.Admin.CreateTestCategory在另一层,它没有实现IDisposable。 It just makes some EF database calls and those calls are disposed in their own way using Repository pattern, so no worries there. 它只是进行一些EF数据库调用,而这些调用使用存储库模式以自己的方式处理,因此不必担心。 But in this controller I created an object obj of that class. 但是在此控制器中,我创建了该类的对象obj After working it out I want to destroy/dispose that obj manually. 解决后,我想手动销毁/处置该obj So the line I commented out, is this the only way to dispose obj ? 所以我注释掉这行,这是处置obj的唯一方法吗?

The reason I did not make BLL.Admin.CreateTestCategory to implement IDisposable is that, there might be a hundred classes like it. 我没有使BLL.Admin.CreateTestCategory实现IDisposable的原因是,可能有一百个类似的类。 I dont want to go to each one and implement IDisposable then use the using block, its painful, instead I want to just dispose it manually after creating it. 我不想去每个都实现IDisposable,然后使用using块,它很痛苦,相反,我只想在创建它之后手动进行处理。 I also dont want to wait for GC. 我也不想等待GC。 So what is the perfect reliable way of doing it? 那么,完美的可靠方法是什么呢?

This question has already been answered in a roundabout way in the comments on the question itself, but to sum up what CodingYoshi, Evk, and Fabjan have said there... 在问题本身的评论中,已经以一种round回的方式回答了这个问题,但总结一下CodingYoshi,Evk和Fabjan在那儿所说的话...

IDisposable is for cleaning up resources that are not managed by the .NET runtime. IDisposable用于清除不受.NET运行时管理的资源。 If you need to clean up connections to databases, file locks, etc, then you really should be using IDisposable . 如果您需要清理与数据库,文件锁等的连接,那么您确实应该使用IDisposable For managed memory, the garbage collector will take care of it better than you can in almost any circumstances. 对于托管内存,垃圾收集器将在几乎任何情况下都比您更好地处理它。 Destructors can be used, but are generally not necessary. 可以使用析构函数,但通常不是必需的。

References: 参考文献:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM