Task

1. Using Task.Run

csharp

using System;

using System.Threading.Tasks;


class Program

{

    static async Task Main(string[] args)

    {

        await Task.Run(() => DoWork());

    }


    static void DoWork()

    {

        // Simulate some work

        Console.WriteLine("Work is being done...");

    }

}


csharp

using System;

using System.Threading.Tasks;


class Program

{

    static async Task Main(string[] args)

    {

        await Task.Factory.StartNew(() => DoWork());

    }


    static void DoWork()

    {

        // Simulate some work

        Console.WriteLine("Work is being done...");

    }

}


3. Using Task Constructor and Start Method

csharp

using System;

using System.Threading.Tasks;


class Program

{

    static async Task Main(string[] args)

    {

        var task = new Task(() => DoWork());

        task.Start();

        await task;

    }


    static void DoWork()

    {

        // Simulate some work

        Console.WriteLine("Work is being done...");

    }

}


4. Using Async and Await

csharp

using System;

using System.Threading.Tasks;


class Program

{

    static async Task Main(string[] args)

    {

        await DoWorkAsync();

    }


    static async Task DoWorkAsync()

    {

        // Simulate some work

        await Task.Delay(1000);

        Console.WriteLine("Work is being done...");

    }

}


5. Using Parallel.ForEach with Task

csharp

using System;

using System.Collections.Generic;

using System.Threading.Tasks;


class Program

{

    static async Task Main(string[] args)

    {

        var list = new List<int> { 1, 2, 3, 4, 5 };

        var tasks = new List<Task>();


        Parallel.ForEach(list, item =>

        {

            tasks.Add(Task.Run(() => DoWork(item)));

        });


        await Task.WhenAll(tasks);

    }


    static void DoWork(int item)

    {

        // Simulate some work

        Console.WriteLine($"Work is being done on item {item}...");

    }

}


These are just a few ways to run tasks in C#. Each method has its own use case, depending on your needs.