Thursday, 5 January 2012

How to fire and Forget a method in c#


iam not using begin invoke method for fear of potential leaks
first lets create class called AsyncHelper As Follows:
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());
            }
        }
    }




next Create a webpage  and Write to delegate to fire  a method and code will be as follows:

//Delegate Declartion

 delegate  int AddDelegate( int a,int b);
    protected void Page_Load(object sender, EventArgs e)
    {
//Invoking delegate and firing it
        AddDelegate d = new  AddDelegate(add);
        AsyncHelper.FireAndForget(d, 2, 3);


    }
// Method body
 public  int add(int a,int b)
 {
     
     return a + b;
 }

}