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