by Mikael Henriksson
14. June 2009 20:45
I just recently had a threading issue in asp.net believe it or not. The issue was that IIS didn’t like the instance variables on the page so sometimes it was shared between different visitors. So removing the instance variables in asp.net means I had to pass classes and parameters around. I ended up with a solution similar to this.
protected void Page_Init(object sender, EventArgs e)
{
var visitor = new VisitorInfo();
SetContentTypeDynamically(visitor);
EnableCache();
Page_Load(visitor, new EventArgs());
}
protected void Page_Load(object sender, EventArgs e)
{
VisitorInfo visitor = sender as VisitorInfo ?? new VisitorInfo();
// do tons of work here
divPageContent.InnerHtml =
HttpUtility.HtmlDecode(page) + divPageContent.InnerHtml;
Page_LoadComplete(visitor, new EventArgs());
}
protected void Page_LoadComplete(object sender, EventArgs e)
{
var visitor = sender as VisitorInfo;
if (visitor != null)
{
LogVisit(visitor);
visitor.Dispose();
}
}
This was working perfectly or so I thought. A colleague detected that the pages was loaded twice actually everything was performed twice. So there was two pages loaded in the container divPageContent. Not so good in other words.
In the page directive of the .aspx file you can set it to false.
<%@ Page Language="C#"
AutoEventWireup="false"
CodeBehind="Class.aspx.cs"
Inherits="Namespace.Class"
EnableViewState="false" %>
Now if you do this you will get an empty page because there are no automatic even wireup done for you but it’s a quick fix. I needed to add a constructor for the class saying to initialize a page_init event.
public Welcome()
{
Page.Init += new EventHandler(Page_Init);
}
Question I have not answered yet though is if I can replace the the page events with regular methods. I’ll experiment on that tomorrow.