简体   繁体   中英

How to Properly dispose an object without IDisposable

In my ASP.NET MVC app I have a controller like this:

[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. It just makes some EF database calls and those calls are disposed in their own way using Repository pattern, so no worries there. But in this controller I created an object obj of that class. After working it out I want to destroy/dispose that obj manually. So the line I commented out, is this the only way to dispose obj ?

The reason I did not make BLL.Admin.CreateTestCategory to implement IDisposable is that, there might be a hundred classes like it. 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. I also dont want to wait for 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...

IDisposable is for cleaning up resources that are not managed by the .NET runtime. If you need to clean up connections to databases, file locks, etc, then you really should be using 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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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