Fire And Forget class for ASP.NET

To reply the email I received this week about an old post of mine from 2005 that I cannot find, I did some digging. This is the class to create a thread for a process that takes a long time to run in ASP.NET without much ADO.

public class AsyncHelper
    {
        class TargetInfo
        {
            internal TargetInfo(Delegate d, object[] args)
            {
                Target = d;
                Args = args;
            }

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

        private static WaitCallback dynamicInvokeShim = new WaitCallback(DynamicInvokeShim);

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

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

Hope this helps

Cheers

Al

Published Thursday, May 14, 2009 11:54 PM by albertpascual
Filed under: , ,

Comments

# re: Fire And Forget class for ASP.NET

Friday, May 15, 2009 3:17 AM by Justin

ThreadPool.QueueUserWorkItem

You would like to see the return value to see if this call succeeded. This method won't throw an exception - it just returns false if it needs to throw the silent treatment that the girlfriends are naturally good at.

# re: Fire And Forget class for ASP.NET

Friday, May 15, 2009 9:58 AM by Javier

Can you give an usage example please.

# re: Fire And Forget class for ASP.NET

Tuesday, May 17, 2011 8:38 PM by weblogs.asp.net

Fire and forget class for asp net.. Keen :)

# re: Fire And Forget class for ASP.NET

Wednesday, November 23, 2011 8:31 AM by Rodrigo

Hey, thankx a lot I've searched for ages, and none of the aproches worked like yours!

Perfect!