Don't wait for your Page_Load to finish if you don't have to.

I spent many times answering this question at http://forums.asp.net , so I thought to put in a post the answer, so I can do a simple link.

How to spoon a thread on the Page_Load so you don't have to wait for the page load rendering controls.

Note: This is not for any control, this is for things like writing to a Log file or to a database. You won't be able to do anything where you need the server context.

Add the code on the Page_Load to fire the method LogSomething in the background:

protected void Page_Load(object sender, EventArgs e) 
    { 
        if (Page.IsPostBack == false) 
        { 
            MyDelegate myDelegate = new MyDelegate(LogSomething); 
            MyFireAndForget(myDelegate); 
        } 
    }

 

define the internal class with the delegate information:

class Info 
        { 
            internal Info(Delegate d, object[] args) 
            { 
                Tar = d; 
                Args = args; 
            } 

            internal readonly Delegate Tar; 
            internal readonly object[] Args; 
        }

private static WaitCallback dynamicInvokeShim = new WaitCallback(DynamicInvokeShim); 

        public static void MyFireAndForget(Delegate d, params object[] args) 
        { 
            ThreadPool.QueueUserWorkItem(dynamicInvokeShim, new Info(d, args)); 
        } 

        static void DynamicInvokeShim(object o) 
        { 
            try 
            { 
                Info ti = (Info)o; 
                ti.Target.DynamicInvoke(ti.Args); 
            } 
            catch (Exception ex) 
            { 
                // Only use Trace as is Thread safe 
                System.Diagnostics.Trace.WriteLine(ex.ToString()); 
            } 
        }

That easy. Please follow me at Twitter or check GeoTwitter today.

Cheers

Al

Published Wednesday, May 07, 2008 11:31 PM by albertpascual
Filed under: , , ,

Comments

# re: Don't wait for your Page_Load to finish if you don't have to.

Thursday, May 08, 2008 4:09 AM by Technical Support Section

wow, nice post! *following you*

# Interesting Finds: 2008.05.11

Saturday, May 10, 2008 11:13 PM by gOODiDEA.NET

.NET Don't wait for your Page_Load to finish if you don't have to. How to validate a method's arguments

# Interesting Finds: 2008.05.11

Saturday, May 10, 2008 11:13 PM by gOODiDEA

.NETDon'twaitforyourPage_Loadtofinishifyoudon'thaveto.Howtovalidateamethod'sarg...

Leave a Comment

(required) 
(required) 
(optional)
(required)