create a program that uses task.run twice inside a task.run in csharp

To create a program that uses Task.Run twice inside a Task.Run in C#, you can use the following code:

main.cs
using System;
using System.Threading.Tasks;

class Program
{
    static void Main()
    {
        // Start the outer task
        Task.Run(() =>
        {
            Console.WriteLine("Outer task started.");

            // Start the inner task 1
            Task.Run(() =>
            {
                Console.WriteLine("Inner task 1 started.");
                // Do some work...
                Console.WriteLine("Inner task 1 completed.");
            });

            // Start the inner task 2
            Task.Run(() =>
            {
                Console.WriteLine("Inner task 2 started.");
                // Do some work...
                Console.WriteLine("Inner task 2 completed.");
            });

            Console.WriteLine("Outer task completed.");
        });

        Console.ReadLine();
    }
}
821 chars
35 lines

In this code, we're starting an outer task that will run some code, and inside that task, we're starting two inner tasks using Task.Run. The inner tasks will execute in parallel to each other and to the outer task.

Note that the inner tasks are defined using lambda expressions to keep the code concise. Additionally, we're using Console.WriteLine to output some text to the console to show when each task starts and completes.

related categories

gistlibby LogSnag