使用大的静态变量不是一个好主意吗? [英] Is it a bad idea to use a large static variable?

查看:89
本文介绍了使用大的静态变量不是一个好主意吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ASP.NET MVC 4,并且希望加载大量数据并使其在我所有的课程中都可以访问. 这是我的代码的简约示例:

I work with ASP.NET MVC 4 and I want to load a large amount of data and make it accessible in all my class. Here is minimalist sample of my code :

public class MyController : Controller
{
    public static List<MyObject> myList = null;

    public ActionResult Index()
    {
        MyViewModel model = new MyViewModel();
        myList = GetAllData(User.IDentity.Name); // Fill my list with 2k rows
        model.List = myList;

        return View(model);
    }


    public JsonResult GetData(int i)
    {
        return Json(myList.Where(x => x.Data == i));
    }

}

一切都可以在本地使用,但是当我在服务器上崩溃时,多个用户遇到了一些问题(崩溃).

Everything is working with in local but I have some problems with multiple users when I puplish on the server (crash).

我认为我做错了.我确定这些静态数据会导致内存泄漏.

I think I made a mistake. I'm sure I have memory leaks with theses static datas.

如何避免此问题?我应该使用单例吗?

How can I avoid this problem ? Should I use a singleton ?

推荐答案

控制器是无状态的,因此每次对动作的调用都会创建一个新的控制器实例,这将破坏您要达到的目的.也就是说,通过在构造函数中进行实例化可以更好地实例化以下内容:

Controllers are stateless, so each call to an action creates a new instance of the controller, which would defeat the purpose of what you are trying to achieve. That said the following in a better implementation of instantiating the static by doing it in the constructor:

public MyController()
{
    myList = GetAllData(); 
}

但是,我建议不要这样做,因为我认为问题更多是设计中的缺陷或对控制器中状态处理方式的误解-它们是无状态的.

However, I advise against this as I think the issue is more a flaw in your design or a misunderstand of how state is handled in controllers - they are stateless.

在地址注释中添加示例: 通用约定是执行以下操作: 1.去除静电,实际上并没有任何帮助.

adding example to address comment: Common convention would be to do the follow: 1. Remove the static, it really gives you no gain.

然后:

public ActionResult Index()
    {
        MyViewModel model = new MyViewModel();

        model.List = GetAllData(User.IDentity.Name);;

        return View(model);
    }


    public JsonResult GetData(int i)
    {
        var model = GetAllData(User.IDentity.Name).Where(x => x.Data == i).ToList();
        return Json(model);
    }

您不需要静态,客户端对Index和GetData的调用将永远不会在控制器的同一实例中执行,在这种情况下,静态是没有用的.

You don't need the static, client calls to Index and to GetData will never be executed in the same instance of the controller, a static is useless in this instance.

这篇关于使用大的静态变量不是一个好主意吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆