Funciones asíncronas

Enlaces

Permiten mejorar la reactividad de una aplicación. Para ello utilizaremos la palabra reservada async y await.

Veamos un ejemplo a partir de una función que verifica si un número es primo o no.

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

namespace ConsoleApplication1
{
    class Program
    {

        public static bool esPrimo(Int64 nb)
        {
            if (nb < 2)
            {
                return false;
            }
            if (nb == 2)
            {
                return true;
            }
            if (nb % 2 == 0)
            {
                return false;
            }
            int i;
            i = 3;
            while ((i * i <= nb))
            {
                if (nb % i == 0)
                {
                    return false;
                }
                else
                {
                    i++;
                }
            }
            return true;
        }

        public static Int64 cuentaPrimos(Int64 maxi)
        {
            Int64 i;
            Int64 nb;
            {
                nb = 0;
                for (i = 0; i <= maxi; i++)
                {
                    if (esPrimo(i))
                    {
                        nb++;
                    }
                }
            }
            return nb;
        }
        static void Main(string[] args)
        {
            Console.Write("Número máximo para el cálculo: ");
            string maxi;
            maxi = Console.ReadLine();
            Int64 resultado;
            resultado = cuentaPrimos(Int64.Parse(maxi));
            Console.WriteLine(resultado);
            Console.ReadKey();
        }
    }
}

Si la entrada fuera 100000000 puede tardar bastante el cálculo. Para mejorar el comportamiento hay que proporcionar al usuario terminar la ejecución de la aplicación sin necesidad de ir al administrador de tareas de Windows.

 

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

namespace ConsoleApplication1
{
    class Program
    {

        public static bool esPrimo(int nb)
        {
            if (nb < 2)
            {
                return false;
            }
            if (nb == 2)
            {
                return true;
            }
            if (nb % 2 == 0)
            {
                return false;
            }
            int i;
            i = 3;
            while ((i * i <= nb))
            {
                if (nb % i == 0)
                {
                    return false;
                }
                else
                {
                    i++;
                }
            }
            return true;
        }

        // función asíncrona
        public static async Task cuentaPrimos(int maxi)
        {
            int resultado;
            resultado = await Task.Run (() =>
            {
                int i;
                int nb;
                {
                    nb = 0;
                    for (i = 0; i <= maxi; i++)
                    {
                        if (esPrimo(i))
                        {
                            nb++;
                        }
                    }
                }
                return nb;
            });
            return resultado;
        }

        static async Task procesamiento(int maxi)
        {
            int resultado;
            resultado = await cuentaPrimos(maxi);
            Console.WriteLine(resultado);
            Console.WriteLine("*********************");
        }

        static void Main(string[] args)
        {
            Console.Write("Número máximo para el cálculo: ");
            string maxi;
            int mx;
            maxi = Console.ReadLine();
            mx = int.Parse(maxi);
            procesamiento(mx);
            Console.WriteLine("Para salir pulsa cualquier tecla.");
            Console.ReadKey();
            
        }
    }
}