Free Web Development Online Tutorials, Learn to Code
Creating a c# task, return a task c#, start a task c#, await a task c#

C# Task Example

C# Task example, Task comes under Threading namespace, you need to add reference of using System.Threading.Tasks;

Start a task c#

Create a simple C# task object without any method

Task t = Task.Delay(100);

Create a task object with an Action. When you say Task.Run() it will always take a method name.

Task t1 = Task.Run(()=>Method1());
Here are commonly useful methods in Task
  • Task.Run

    Run method takes an action name as parameter

    Task t1 = Task.Run(()=>Method1());
    
  • Task.Delay

    Delay method is used when you want some task to be completed after some time delay, you can specify time in milliseconds.

    Task t = Task.Delay(100);
    

Cerate a simple task as a method.

public Task GetData()
{
    create a  task object with an Action.
    */
    Task t1 = Task.Run(()=>Method1());
    return t1;
}

Create a task object of specific data type with an Action. In earlier example, we have seen how to create a task, now we see how to create a task with some specific data type, for example, here I have created a task that will get student information based on student id and return a Student object.

public Task<Student> GetStudent(int studentId)
{
    /*
        create a task object of specific data type with an Action. 
    */
    Task<Student> t1 = Task.Run(() => getStudentInfo(studentId));
    return t1;
}
Student getStudentInfo(int studentId)
{
    Student s = new Student();
    //Get student details from database
    return s;
}

Return custom object list using Task, here in example below I have a student list, so in my function I am returning the student list Task<IList<Student>> GetStudents() from the code below

public Task<IList<Student>> GetStudents()
{          
    Task<IList<Student>> t2 = Task.Run(() => getAllStudents());
        
    return t2;
}
IList<Student> getAllStudents()
{
    IList<Student> s = new List<Student>();
    //Get student details from database
    return s;
}

You should also look at following tutorials

Comment
Name
Email
Website
Subscribe
 
free C# tutorial online


C# Enums Example
Other Online Tutorial

C# .net Interview Questions Answers

.Net C# Examples | Join .Net C# Course