Monday, June 18, 2012

Using Tasks in APM


The “FromAsync” method in the Task Framework helps to build Task object from the “Async” methods (APM). Below code is an example of the same.

Also beside, using  “FromAsync” method, “TaskCompletionSource” object helps to set the result in the callback method.
Below code has both as examples.
namespace ConsoleApplication5
{
    class Program
    {
        delegate int delSum(int a, int b);
        static void Main(string[] args)
        {
            try
            {
                delSum oSum = new delSum((a1, a2) =>
                {
                    Thread.Sleep(2000);
                    return a1 + a2;
                });

                //Using "From Async" method to convert APM to TAP
                Task<int> aa = Task<int>.Factory.FromAsync(
                    oSum.BeginInvoke, oSum.EndInvoke, 4, 5, null);
                aa.ContinueWith(t => Console.WriteLine("using from async method " + t.Result));

                //Using "Task Completion Source", to set the task result from IAsyncResult
                TaskCompletionSource<int> source = new TaskCompletionSource<int>();
                oSum.BeginInvoke(8, 9, ar =>
                     {
                         try
                         {
                             source.SetResult(oSum.EndInvoke(ar));
                         }
                         catch (Exception exp)
                         {
                             Console.WriteLine("Error : " + exp.Message);
                         }
                     }, null);

                source.Task.ContinueWith(t => Console.WriteLine("using task completion source " + t.Result));
            }
            catch (Exception exp)
            {
                Console.WriteLine("Error : " + exp.Message);
            }
            Console.Read();
        }

    }
}



No comments: