Tasks, Await and Async to manage asynchronous methods and promises

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

namespace AwaitTaskTest
{
    class Program
    {
        static void Main(string[] args)
        {
            //---------------------------
            //This is a normal sync call
            //---------------------------

            Console.WriteLine("Sync call begin");
            PrintPrimes();
            Console.WriteLine("Sync call end\n");

            //--------------------------------
            //This is an async call to
            //async methods using async/await
            //--------------------------------

            Console.WriteLine("Async call begin");
            PrintPrimesAsync();
            Console.WriteLine("Async call end\n");

            //-----------------------------
            //This is an async call to
            //sync methods using a promise
            //-----------------------------

            Console.WriteLine("Promise call begin");

            //Defer
            var deferred = Task.Factory.StartNew(() =>
            {
                return GetPrimes(1, 1000000);
            });

            //Then
            deferred.ContinueWith(d =>
            {
                Console.WriteLine("Count: {0}", d.Result.Count());
            }, TaskContinuationOptions.OnlyOnRanToCompletion);

            //Fail
            deferred.ContinueWith(d =>
            {
                Console.WriteLine("Exception: {0}", d.Exception);
            }, TaskContinuationOptions.OnlyOnFaulted);
            Console.WriteLine("Promise call end\n");

            Console.ReadKey();
        }

        //--------------
        // Sync Methods
        //--------------

        private static void PrintPrimes()
        {
            var primes = GetPrimes(1, 1000000);
            Console.WriteLine("Count: {0}", primes.Count());
        }

        private static IEnumerable<int> GetPrimes(int min, int count)
        {
            return Enumerable.Range(min, count).Where
                (n => Enumerable.Range(2, (int)Math.Sqrt(n) - 1).All(i =>
                    n % i > 0));
        }

        //--------------
        // Async Methods
        //--------------

        private static async void PrintPrimesAsync()
        {
            //When an await call is found the method will return
            //immediately and will continue to run asynchronously
            var primes = await GetPrimesAsync(1, 1000000);
            Console.WriteLine("Count: {0}", primes.Count());
        }

        private static Task<IEnumerable<int>> GetPrimesAsync(int min, int count)
        {
            return Task.Run(() => Enumerable.Range(min, count).Where
                (n => Enumerable.Range(2, (int)Math.Sqrt(n) - 1).All(i =>
                    n % i > 0)));
        }
    }
}

And here is the output:

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