Uthman Rahimi February 2016

How to destory instance of class when finished Action

I use MVVM in my project . first at all see Edit Action:

[HttpGet]
    public async virtual Task<ActionResult> Edit(int code)
    {
        var attributeModel = await _attributeService.GetAsync(code);
        EditAttributeViewModel attributeViewModel = mapper.Map(attributeModel, new EditAttributeViewModel());
        return View(attributeViewModel);
    }

in ViewModel I count instance like this :

 public class EditAttributeViewModel
{
    private static int counter = 0;
    public EditAttributeViewModel()
    {
        Interlocked.Increment(ref counter);
    }
    ~EditAttributeViewModel()
    {
        Interlocked.Decrement(ref counter);
    }
}

when Finished Edit Action and change controller , comeback again to that Edit Action and when see counter always it increase , While I am moving between pages.I do not want to use too much memory, for do this I Override Dispose Method in controller like this :

    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);

    }

but It doest chnage and counter always increase .

How can I Clear Instance when Finshed ActionMethod

Answers


PC Luddite February 2016

Because counter is marked static, it will persist throughout the lifetime of the application (agnostic to specific instance of classes). If this is not the desired result, and you want a fresh instance of counter with each instance of the class, remove the static keyword.

 private int counter = 0;

This will create a new instance of counter for each instance of EditAttributeViewModel.


Tseng February 2016

Unlike in C++, you can't free memory on demand. The Dispose pattern is there to release unmanaged resources (file handlers, connections, or pictures that are unmanaged, read: reserved outside of the .Net Memory management as well as anything that uses IntPtr).

All you can do is, to set all references to null and call .Dispose() on all disposable types in your class, then wait until the garbage collection pick them up.

Depending no how your application utilize memory, this may be sooner or later. If your application often instantiates and unreferencing objects this may happen sooner, if your application doesn't it may take longer.

You shouldn't depend on that the finalizer (that looks like deconstructor in C++) is called or when. GC calls it, when it's cleaning it up. But only if you haven't suppressed it (which you typically do inside Dispose method).

Post Status

Asked in February 2016
Viewed 1,678 times
Voted 10
Answered 2 times

Search




Leave an answer