"No one is harder on a talented person than the person themselves" - Linda Wilkinson ; "Trust your guts and don't follow the herd" ; "Validate direction not destination" ;

May 06, 2012

.NET 4.0 Working with Tasks

This post is about Task library. This library would be very useful for load simulator. Posted below sample examples.

// -----------------------------------------------------------------------
// <copyright file="LoadSimulator.cs" company="Microsoft">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Threading.Tasks;

namespace SampleExercises
{
    static class LoadSimulator
    {
        public static int i = 10;
        static void Main(string[] args)
        {
            string status = "";

             //Task with return status
            Task<string> ThreadsCreation = Task<string>.Factory.StartNew(() =>
            {
                status = methodA();
                return status;
            });

            //Wait for Task Completion
            ThreadsCreation.Wait();
            Console.WriteLine("Status value is " + status);
            Console.ReadLine();

            //Taskwith no return status
             var noReturnTask = new Task(() => methodB());

            //Start The Task
            noReturnTask.Start();
            Console.ReadLine();

        }

        public static string methodA()
        {
            Console.WriteLine("i count is" + i++);
            return i.ToString();
        }
        public static void methodB()
        {
            Console.WriteLine(" This is am empty Task");
        }
    }
}


Reference - Link1


Happy Learning!!!

No comments: