• Tasks in C#



    Tasks in C# is nothing but an operation or a work that executes in asynchronous manner. It was introduced in .Net framework 4.0 to support asynchronous functionality, in-fact the Task Parallel Library which is known as TPL is based on the concept of Tasks.

    C#.NET

    Tasks in C#
    Tasks in C# is nothing but an operation or a work that executes in asynchronous manner. It was introduced in .Net framework 4.0 to support asynchronous functionality, in-fact the Task Parallel Library which is known as TPL is based on the concept of Tasks.

    What is a Task in C# ?

    In C# Task is basically used to implement asynchronous programming model, the .Net runtime executes a Task object asynchronously on a separate thread from the thread pool.

    The Task Scheduler in .Net framework is responsible to execute the Task , by default it requests a worker thread from the Thread Pool to execute the Task . Here, the thread pool determines, whether to create a new thread or reuse an existing thread from the thread pool to execute the operation.

    Creating Tasks in C# ?

    To create a Task in C#, first you need to import System.Threading.Tasks namespace in to your program, then you can use the Task class to create object and access its properties.

    //Create a task instance 
     Task t = new Task(PrintEvenNumbers);
    //Start the task 
    t.Start();
    
    • 1
    • 2
    • 3
    • 4

    Example – 1 : Creating Tasks in C# using Task class and Start method

    In below example, we have created a Task object as Task t , passing the method PrintEvenNumbers; in the constructor, then we invoke the Task t by t.Start(); method.

    using System;
    using System.Threading.Tasks;
    namespace TaskInCshap
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a task instance
                Task t = new Task(PrintEvenNumbers);
                //Start the task
                t.Start();
                Console.Read();
            }
            public static void PrintEvenNumbers()
            {
                Console.WriteLine("Even numbers less than 10");
                for (int i = 0; i <= 10; i++)
                    if(i%2 == 0)
                        Console.WriteLine("Number : {0}", i);        
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    When we run above example, it generates below output, here the task executes in a separate thread and prints the even numbers on the console window.
    在这里插入图片描述

    Different ways of creating Tasks in C#:

    There are various ways available in C#.Net 4.0 to create a Task object. Please find some of the different ways as follows.

    Task Creation using Factory method :

    We can also use Task.Factory() method to creates a task instance and invoke it in a single line of code, as follows.

    //Create a task and invoke it
    Task.Factory.StartNew(PrintEvenNumbers);
    
    • 1
    • 2

    Task creation using Action Generic Delegate :

    You can use below syntax to create a task using Action type (Generic Delegate) , In below code example, we have created a task object and then invoking it.

    //Create a Task using Action delegate
    Task t = new Task(new Action(PrintEvenNumbers));
    //Invoke Task
    t.Start();
    
    • 1
    • 2
    • 3
    • 4

    Task creation using a Delegate :

    In below code sample, we are using delegate keyword to create a task instance and then invoking it.

    //Create a Task using delegate
    Task t = new Task(delegate { PrintEvenNumbers(); });
    //Invoke Task
    t.Start();
    
    • 1
    • 2
    • 3
    • 4

    Task creation using Action Generic Delegate :

    You can use below syntax to create a task using Action type (Generic Delegate) , In below code example, we have created a task object and then invoking it.

    //Create a Task using Action delegate
    Task t = new Task(new Action(PrintEvenNumbers));
    //Invoke Task
    t.Start();
    
    • 1
    • 2
    • 3
    • 4

    Task creation using a Delegate :

    In below code sample, we are using delegate keyword to create a task instance and then invoking it.

    //Create a Task using delegate
    Task t = new Task(delegate { PrintEvenNumbers(); });
    //Invoke Task
    t.Start();
    
    • 1
    • 2
    • 3
    • 4

    Similarly, we can also use Task.Run() method to create a task object and invoke it in single line, as follows.

    //Invoke it directly using Run method
    Task t = Task.Run(delegate { PrintEvenNumbers(); });
    
    • 1
    • 2

    Task creation using Lambda and named method :

    In below code sample, we are using lambda and named method expression to create a task instance and then invoking it.

    //Creating a Task instance using lambda and named method 
    Task t = new Task(() => PrintEvenNumbers());
    //Invoke Task
    t.Start();
    
    • 1
    • 2
    • 3
    • 4

    Similarly we can also use Task.Run() method to create a task object and invoke it in single line, as follows.

    //Invoke it directly using Run method
    Task t = Task.Run(() => PrintEvenNumbers());
    
    • 1
    • 2
  • 相关阅读:
    【算法优选】双指针专题——壹
    【Java面试八股文宝典之基础篇】备战2023 查缺补漏 你越早准备 越早成功!!!——Day09
    五、分页总结
    第六章、Python 装饰函数
    JavaSE 第七章 面向对象基础(下)静态&枚举&抽象类
    Java数据结构与算法(爬楼梯动态规划)
    论文阅读--Diffusion Models for Reinforcement Learning: A Survey
    0905(047天 大数02 hadoop环境搭建)
    基于51单片机的简易可调时钟闹钟Proteus仿真
    气膜球幕影院:科技创新的结晶—轻空间
  • 原文地址:https://blog.csdn.net/wojiuguowei/article/details/126888575