65.9K
CodeProject is changing. Read more.
Home

Asynchronous execution with anonymous method pattern

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.71/5 (4 votes)

Jan 5, 2010

CPOL
viewsIcon

13521

This is my helper class: public class AsynchronousMethodHelper { private static Delegate _method; private static Delegate _callBack; public static void AsynchronousExecution(Delegate method, Delegate callBack) { _method = method; ...

This is my helper class:
    public class AsynchronousMethodHelper
    {
        private static Delegate _method;
        private static Delegate _callBack;

        public static void AsynchronousExecution(Delegate method, Delegate callBack)
        {
            _method = method;
            _callBack = callBack;
            BackgroundWorker bgWorker = new BackgroundWorker();
            bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
            bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);
            bgWorker.RunWorkerAsync();
        }

        private static void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            _callBack.DynamicInvoke(null);
        }

        private static void bgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            _method.DynamicInvoke(null);
        }
    }
How to use:
            FormProgressBar frmProgress = new FormProgressBar ();
            frmProgress.Show();
            AsynchronousMethodHelper.AsynchronousExecution(new ThreadStart(delegate()
            {
                // anonymous  method for asynchronous execution
                for (int i = 0; i <= 2; i++)
                {
                    // fake execution  (delay 2 seconds)
                    Thread.Sleep(1000);
                }
            }), new ThreadStart(delegate()
            {
                // call back
                frmProgress .Hide();
            }));