Task Parallel Library – Async await Task CASE STUDY

Case Study1: When the function does not return any value

using System;

using System.Threading.Tasks;

using System.Threading;

class Life

{

    public static void Main()

    {

        LongTask();

        Console.WriteLine(“Lets go!!”);

        Console.ReadLine();

    }

    public async static void LongTask()

    {

        await Task.Run(()=>{

        Thread.Sleep(5000);

        Console.WriteLine(“Bro, Wait for 5 seconds”);

        });

    }

}

Case Study2: When the function does returns any value (Injection Technique will be used)

 

// Main()—calls-àF1()—-calls–àLongTask()

 

using System;

using System.Threading;

using System.Threading.Tasks;

class Life

{

    public static void Main()

    {

        F1();

        Console.WriteLine(“Lets go!!”);

        Console.ReadLine();

    }

    public async static void F1()

    {

        Task<int> x = LongTask();

        int y = await x;

        Console.WriteLine(y);

        Console.ReadLine();

    }

    public async static Task<int> LongTask()

    {

        int y;

        return await Task.Run(()=>{

            Thread.Sleep(5000);

            y=15;

            return 15;

        });

    }

}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.