TASK.FACTORY AND TASK

				
					
internal static class Program
{
    public static void Print(char c)
    {
        int i = 500;
        while (i-- > 0)
        {
            System.Console.WriteLine(c);
        }
    }
    public static void Main()
    {
        //doing two thing at same time
        //1. making the task
        //2. starting it
        Task.Factory.StartNew(() => Print('A'));

        //or 
        //-- you ought to start the task in this case
        var t = new Task(() => Print('G'));
        t.Start();

        //below runs in main thread
        Print('M');

        System.Console.WriteLine("---end---");

    }
}
				
			
				
					
internal static class Program
{
    public static void PrintOverLoaded(object s)
    {
        int i = 500;
        while (i-- > 0)
        {
            System.Console.WriteLine(s);
        }
    }
    public static void Main()
    {
        //overloaded method
        //public Task StartNew(Action<object?> action, object? state);

        Task.Factory.StartNew(PrintOverLoaded, "Anurag");

        //overloaded method
        //public Task StartNew(Action<object?> action, object?
        Task t = new Task(PrintOverLoaded, "Nayak");
        t.Start();

        System.Console.WriteLine("---Overload method end---");

    }
}
				
			
				
					
internal static class Program
{

    public static string? ToUpperCase(object obj)
    {
        System.Console.WriteLine($"Task id is {Task.CurrentId}");
        return obj.ToString().ToUpper();
    }
    public static void Main()
    {
        string name1 = "anurag";
        string name2 = "nayak";
        var task1 = new Task<string>(ToUpperCase, name1);
        task1.Start();

        var task2 = Task.Factory.StartNew<string>(ToUpperCase, name2);

        System.Console.WriteLine($"converting to upper case {task1.Result}");
        System.Console.WriteLine($"converting to upper case {task2.Result}");
        System.Console.WriteLine("---Ending generic task method!!---");
    }
}
				
			
				
					Task id is 1
Task id is 2
converting to upper case ANURAG
converting to upper case NAYAK
---Ending generic task method!!---
anuragnayak@192 helloworld % 
				
			

Leave a Comment