A day with .Net

My day to day experince in .net

C# Async HelloWorld

Posted by vivekcek on August 26, 2012

You need Visual Studio 2012 to run this code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    /// <summary>
    /// Program Class.
    /// </summary>
    public static class Program
    {
        /// <summary>
        /// Entry Point
        /// </summary>
        /// <param name="args">Command Line Parameters.</param>
        public static void Main()
        {
             Calculate();
             Console.WriteLine("Asynchronous Execution Started");
             Console.ReadLine();
        }

        /// <summary>
        /// Async Method.The method marked as async.
        /// </summary>
        public static async void Calculate()
        {
            Task<int> t = Task<int>.Factory.StartNew(() =>
                {
                    int i = 0;
                    for (; i < 100; i++)
                    {
                        System.Threading.Thread.Sleep(10);
                    }

                    return i;
                });

            await t;//At this point Calculate Method started asynchronous waiting
            Console.WriteLine(t.Result);
        }
    }
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s