0
0
C Sharp (C#)programming~5 mins

Task and Task of T types in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Tasks help you run work in the background without stopping your program. Task<T> lets you get a result back when the work is done.

When you want to do something that takes time without freezing your app, like loading a file.
When you want to run multiple things at the same time and wait for all to finish.
When you want to get a value back from a background job, like fetching data from the internet.
When you want to write cleaner code that handles waiting for work to finish easily.
Syntax
C Sharp (C#)
Task task = Task.Run(() => { /* work here */ });

Task<T> taskWithResult = Task.Run(() => { return value; });

Task is for work that does not return a value.

Task<T> is for work that returns a value of type T.

Examples
This runs some work in the background without returning a result.
C Sharp (C#)
Task task = Task.Run(() => {
    Console.WriteLine("Doing work...");
});
This runs work that returns the number 42 when done.
C Sharp (C#)
Task<int> task = Task.Run(() => {
    return 42;
});
This waits for the task to finish and gets the result 15.
C Sharp (C#)
int result = await Task.Run(() => 10 + 5);
Sample Program

This program shows how to run a task that does some work and waits for it. Then it runs a task that returns a number and prints that number.

C Sharp (C#)
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        // Task without result
        Task task = Task.Run(() => {
            Console.WriteLine("Starting work...");
            Task.Delay(1000).Wait(); // Simulate work
            Console.WriteLine("Work done.");
        });

        await task; // Wait for task to finish

        // Task with result
        Task<int> taskWithResult = Task.Run(() => {
            Task.Delay(500).Wait(); // Simulate work
            return 123;
        });

        int result = await taskWithResult;
        Console.WriteLine($"Result from task: {result}");
    }
}
OutputSuccess
Important Notes

Use await to wait for a Task or Task<T> to finish without blocking your program.

Task.Delay simulates waiting without blocking the thread.

Task<T> lets you get a value back from background work easily.

Summary

Task runs work without returning a value.

Task<T> runs work and returns a value of type T.

Use await to get results or wait for tasks to finish smoothly.