2013-12-12 41 views
1

我想将在Global.asax中定义的ArrayList公开给所有会话。这里是一些来自Global.asax和Default.aspx的代码:global.asax问题 - 为ASP.NET中的所有新会话授予ArrayList

public class Global : System.Web.HttpApplication 
{ 

    public ArrayList userNameList = new ArrayList(); 
    protected void Application_Start(object sender, EventArgs e) 
    { 

    } 

    protected void Session_Start(object sender, EventArgs e) 
    { 

    } 
} 


public partial class _Default : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     Global global = new Global(); 
     User user = new User(); 
     user.username = TextBox1.Text; 
     global.userNameList.Add(user); 
     if (global.userNameList.Count != 0) 
     { 
      foreach (User u in global.userNameList) 
      { 
       ListBox1.Items.Add(String.Format(u.username)); 
      } 
     } 
    } 
} 

请告诉我我做错了什么。谢谢:)

+0

欢迎来到SO,Krystian。欣赏代码示例。如果你描述了你所看到的问题,你可能会得到更多的帮助。 – Rap

回答

0

你做错了第一件事就是尝试实例化页面中的全局类。这不会像你期望的那样工作。

如果你想所有会话之间共享一个ArrayList(或其他任何东西),你应该使用应用程序状态来代替: -

http://msdn.microsoft.com/en-us/library/ms178594(v=vs.100).aspx

你也应该同步到共享状态访问读了根据你在做什么,可能会有潜在的线程问题。

0

删除您在Global.asax文件中使用任何东西,在你的aspx页面使用此代码

public partial class _Default : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     User user = new User(); 
     user.username = TextBox1.Text; 


     if (Cache["userList"] == null) 
      Cache["userList"] = new ArrayList(); 

     ((ArrayList)Cache["userList"]).Add(user); 

     foreach (User u in (ArrayList)Cache["userList"]) 
     { 
      ListBox1.Items.Add(String.Format(u.username)); 
     } 
    } 
} 

确保重构你的代码,因为你会很容易碰到的维护问题,再加上它不是单元测试的所有。希望它有帮助

狮子座