此代码会导致我的 MVC 应用程序内存泄漏吗?
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);
}
}
SomeViewModel 是一个大型对象,填充在控制器的操作中。当控制器被处置时,它会被 GC 回收还是从内存中清除?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
控制器中的这个
public SomeViewModel viewModel;
字段没有任何意义。控制器操作是独立的,这意味着如果您首先调用SomeAction
来设置该字段的值,然后调用其他一些操作,则不会期望该字段继续存在。所以你应该简单地使用这个:这就是说你当前的代码似乎没有内存泄漏,因为一旦请求结束,Controller 类将有资格进行 GC,因此它的所有实例字段(包括视图模型)。
There is no point of this
public SomeViewModel viewModel;
field in your controller. Controller actions are independant meaning that if you first invokeSomeAction
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: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.
如果 populateViewModel 方法不使用一次性资源(作为数据上下文)或使用和处置它们,那么您的代码应该没问题。
if populateViewModel method does not use disaposable resources (as data context) or uses and disposes them, your code should be fine.