:::: MENU ::::

Monday, May 12, 2008

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());

            }

        }

 

Categories: