Thursday, October 13, 2016

#C# Why Task introduced in C#?

Why Task introduced in C#?
.net framework provides System.Threading.Tasks.Task class to let you create threads and run them asynchronously. Queuing a work item to a thread pool is useful, but there is no way to know when the operation has finished and what the return value is.So that the reason Microsoft introduced the concept of Task.
Task is an object that represents some work that should be done.

Example:

public class Program {
    public static void Main() {
        // use an Action delegate and named method
        Task task1 = new Task(new Action(printMessage));
        // use an anonymous delegate
        Task task2 = new Task(delegate { printMessage() });
        // use a lambda expression and a named method
        Task task3 = new Task(() => printMessage());
        // use a lambda expression and an anonymous method
        Task task4 = new Task(() => { printMessage() });

        task1.Start();
        task2.Start();
        task3.Start();
        task4.Start();
        Console.WriteLine("Main method complete. Press <enter> to finish.");
        Console.ReadLine();
    }
    private static void printMessage() {
        Console.WriteLine("Hello, world!");
    }

}