Manish Pansiniya's Blog

.NET, C#, Javascript, ASP.NET and lots more…:)

Threading in ASP.NET

leave a comment »

You can do the same method which we can do in form based application. You need to be sure about the logic you are doing in the Thread.

Suppose you are accessing, Session in the thread and if thread is taking longer while the page code’s Response ended. Then you have problem as when response is ended the session variable of request is cleared.

So if you are accessing Request.Session , it will show null value after response is added.

You might call thread on page.init and in page load, you can call Join to wait for thread to complete and go ahead.

Below is sample code: I have passed context as thread’s parameter. It will be used fully as I used Join of thread. If I do not use Join then some of the variables is not available in context parameter. The conclusion is we can use thread same way but we need to be sure of page parameters/context parameters which we are passing to thread. That’s it!!!

protected void Page_Load(object sender, EventArgs e)
{
        Thread t = new Thread(new ParameterizedThreadStart(ref CallAnalyticsFunction));
        t.Start(this.Context);
        
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Cache.SetAllowResponseInBrowserHistory(false);

        Response.ContentType = "image/gif";
        Response.AppendHeader("Content-Length", _imgbytes.Length.ToString());
        Response.Cache.SetLastModified(DateTime.Now);
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.BinaryWrite(_imgbytes);
        Response.Flush();

        t.Join();
}
[tweetmeme only_single=”false”]
Advertisements

Written by Manish

October 3, 2010 at 4:06 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: