Click here to Skip to main content
Click here to Skip to main content

Asynchronous execution with anonymous method pattern

By , 15 Feb 2010
 
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();
            }));

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Nitipan

Thailand Thailand
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralThis is a usefull article for me. Thank you very mych :)memberAsutosha19-Aug-10 4:02 
GeneralYou shouldn't use a static classmemberJeremy Hutchinson13-Jan-10 5:14 
GeneralRe: You also shouldn't leave it up to any Delegatememberkornman0013-Jan-10 5:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130617.1 | Last Updated 16 Feb 2010
Article Copyright 2010 by Nitipan
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid