[DotNet]DotNet Asynchronous Programming Pattern

4. August 2010

Delegate BeginInvoke and EndInvoke methods are the fundatmental of c# asynchronous programming. here is a example:

    public class AsyncResultPatternIntroduction {

        delegate void WorkerThreadHandler();

        public void AsyncMain() {

            WorkerThreadHandler workerMethod = null;

            IAsyncResult asyncResult = null;

            workerMethod = new WorkerThreadHandler(DoWork);

            Console.WriteLine("Starting app...");

            asyncResult = workerMethod.BeginInvoke(null, null);

            while (!asyncResult.IsCompleted) {

                Console.Write(".");

                Thread.Sleep(100);

            }

            workerMethod.EndInvoke(asyncResult);

            Console.WriteLine("Ending app...");

        }

 

        public void DoWork() {

            Console.WriteLine("\nDoWork() started...");

            Thread.Sleep(1000);

            Console.WriteLine("\nDoWork() ending...");

        }

    }

 

To create an class with BeginXXX and EndXXX methods: here is a example:

    public class Sum {

        internal delegate UInt64 SumDelegate(UInt64 n);

        SumDelegate sumDelegate = null;

        public Sum() {

            sumDelegate = CalculateSum;

        }

        public IAsyncResult BeginCalculateSum(UInt64 n,

                                     AsyncCallback callback,

                                     object state) {

            return sumDelegate.BeginInvoke(n, callback, state);

        }

 

        public UInt64 EndCalculateSum(IAsyncResult result) {

            return sumDelegate.EndInvoke(result);

        }

        public UInt64 CalculateSum(UInt64 n) {

            UInt64 sum = 0;

            for (UInt64 i = 1; i <= n; i++) {

                checked {

                    // I use checked code so that an OverflowException gets

                    // thrown if the sum doesn't fit in a UInt64.

                    sum += i;

                }

            }

            Thread.Sleep(1000);

            return sum;

        }

    }

 

DotNet

Comments

1/16/2012 11:47:32 PM #
I have surfed the net more than three hours today, and your blog was the coolest of all.
1/16/2012 11:59:41 PM #
Great work dude, u gave nice post to us.This will be very beneficial for all of us here. Thanks for spending the time to discuss this.

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading