我在一个更大的项目中遇到了这个问题,我设法在一个缩小的单页场景中查明并重现了它。该页面有一个单按钮控件btnSubmit
,后面的代码如下:
private int n = 100;
protected void Page_Init(object sender, EventArgs e) {
btnSubmit.Click += btnSubmit_Click;
}
protected void Page_Load(object sender, EventArgs e) {
if (!Page.IsPostBack) {
Session["test"] = "Hello World";
for (int i = 0; i < n; i++) {
using (StreamWriter file = new StreamWriter(Server.MapPath("/sample.txt"), true)) {
file.WriteLine(i);
}
}
} else {
int sessionCount = Session.Count;
string test = Session["test"].ToString();
}
}
void btnSubmit_Click(object sender, EventArgs e) {
}
上面的代码在页面加载时做了两件事。首先,将字符串“Hello World”分配给会话变量test
。第二,将 0 到 99 的整数写入文本文件“sample.txt”的不同行。单击btnSubmit
会触发回发(该按钮不执行任何其他操作,只是回发页面)。回发后,sessionCount = 1
和的值test = "Hello World"
。这是预期的行为,上面的代码运行良好。
现在,如果您更改n = 9000
或任何大整数,在回发时(通过单击btnSubmit
),会话变量Session["test"]
为 null 并且sessionCount = 0
. test
抛出异常,因为Session["test"]
不存在。是什么赋予了?我的开发机器有 6GB 的 RAM,内存不足不太可能是原因,因为处理几千个整数并不需要太多。