Session集合会在一个会话的各个页面中造成“互串”。static的作用域在于整个进程,Session集合的作用域在于会话(不论这个会话中有多少页面),ViewState的作用域才在单个页面。关于“省资源”的观念,什么才省资源?如果连逻辑正确性都做不到,省资源有什么意义吗?其实最省资源的办法就是什么都不做!给你写个demo,自己体会一下页面状态维系的机制:<%@ Page Language="C#" %><script runat="server"> protected int a {get;set;} protected int b { get { object x = ViewState["value_b"]; return x == null ? 0 : (int)x; } set { ViewState["value_b"] = value; } }
public static string str = ""; lock (str )
{ }
lock 好象不对 确实是同一变量 这不过是在各客户端的不同副本
不是这个理。asp.net大多数时候都是在同一个进程中(以多线程方式)处理各个客户端会话请求,只有个别情况才会重新启动进程。是这个“理”。因此,如果你使用共享变量,那么值就“搭界”了。
1楼不是让你试用static,而是让你不要用static。“各客户端的不同副本”是你的想象,没有根据。
那么只能看你的代码修改时的流程了。你写个简单的demo程序复现这个现象出来?!
if (!IsPostBack)
{
reroad();
}
protected void Button1_Click(object sender, EventArgs e)
{
tpage++;
reroad();
}protect void reroad
{
strsql = "select * from tblTiku wher id>" +(tpage*10)+" and id<="+((tpage+1)*10)
cm = new OleDbCommand(strsql, cn);
cn.Open();
dr = cm.ExecuteReader();
while(dr.Read())
{
.............
}
理应各客户端的tpage是不同的,但却互串了
什么“互串”啊。即使是同一个页面,每一次回发时 tpage 不是也都是 0 吗?
{
tpage++;
reroad();
}
你不是在page里边声明protected的变量然后直接使用吗?asp.net页面的生命周期是什么?每一次请求,都创建一个新的page对象,处理各种事件,然后输出html,之后就销毁了这个对象了。当再次请求,又重新创建一个新的page对象。那么你的那些变量值当然又重新初始化了。要维系页面上的状态,使用ViewState。ViewState是开发交互式asp.net程序的灵魂。
protected int a {get;set;}
protected int b
{
get { object x = ViewState["value_b"]; return x == null ? 0 : (int)x; }
set { ViewState["value_b"] = value; }
}
protected void Button1_Click(object sender, EventArgs e)
{
a++;
b++;
} protected void Page_PreRender(object sender, EventArgs e)
{
this.Label1.DataBind();
this.Label2.DataBind();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server" Text="<%# a.ToString() %>" /><br />
<asp:Label ID="Label2" runat="server" Text="<%# b.ToString() %>" /><br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
</form>
</body>
</html>