C# Task example, here we learn how to create task and consume task in C# programming.
Task comes under Threading namespace, you need to add reference of using System.Threading.Tasks;
Create a simple C# task object without any method
Task t = Task.Delay(100);
There are various ways we can create a task object and assign a long running method in it, let’s learn by example below.
Create a task object with an Action. When you say Task.Run() it will always take a method name.
Task t1 = Task.Run(()=>Method1());
Run method takes an action name as parameter
Task t1 = Task.Run(()=>Method1());
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;
}
to learn more about C# Task, You should also look at following tutorials