开发者

Will this code cause memory leak on my MVC application?

开发者 https://www.devze.com 2023-04-10 04:55 出处:网络
public class SomeViewModel { public List<Something> listOfSomethings = new List<Something>();
public class SomeViewModel
{
    public List<Something> listOfSomethings = new List<Something>();
    public Entity EntityObj;
    etc...开发者_如何学编程
    etc..
    ..
}

public class Controller() 
{
    public SomeViewModel viewModel;

    public ActionResult SomeAction() 
    {
        viewModel = populateViewModel();

        return View(viewModel);
    }
}

The SomeViewModel is a large object that is populated in the controller's action. Will it be GC'd or cleared from memory when the controller is disposed?


There is no point of this public SomeViewModel viewModel; field in your controller. Controller actions are independant meaning that if you first invoke SomeAction which sets a value for this field and then invoke some other action do not expect this field to survive. So you should simply use this:

public class HomeController: Controller
{
    public ActionResult SomeAction() 
    {
        var viewModel = populateViewModel();
        return View(viewModel);
    }

    public ActionResult SomeOtherAction()
    {
        var viewModel = populateViewModel();
        return View(viewModel);
    }
}

This being said your current code doesn't seem to have memory leaks because once the request ends the Controller class will be eligible for GC and so all its instance fields including the view model.


if populateViewModel method does not use disaposable resources (as data context) or uses and disposes them, your code should be fine.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号