BobSwanson
BobSwanson

Reputation: 423

Running multiple Task

I'm trying to execute multiple Tasks at the same time

    private static void Main(string[] args)
    {
        while (true) {
            Console.ForegroundColor = ConsoleColor.White;
            Console.Write("Enter number of cart: ");
            var numOfCarts = Convert.ToInt32(Console.ReadLine());

            Console.Write("Enter number of items: ");
            var numOfItems = Convert.ToInt32(Console.ReadLine());
            RunTasks(numOfCarts, numOfItems).Wait();
        }
    }

    public static async Task RunTasks(int numOfCarts, int numOfItems)
    {
        for (var i = 0; i < numOfCarts; i++)
            await Task.Run(() =>
            {
                var color = (ConsoleColor) new Random().Next(0, 15);
                for (var q = 0; q < numOfItems; q++) {
                    Console.ForegroundColor = color;
                    Console.WriteLine("Cart {0} : {1}", i, q);
                }
            });
    }

is this correct implementation? ForegroundColor rarely changes. I would like the console color to be different for each cart.

Upvotes: 0

Views: 47

Answers (1)

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34189

Do not mix up Task.Wait() calls and async / await. In your case, it may lead to deadlock when main thread waits for RunTasks to execute while RunTasks waits for main thread to start continuation.

In your case, you could simply use Task.WhenAll:

private static void Main(string[] args)
{
    while (true) {
        Console.ForegroundColor = ConsoleColor.White;
        Console.Write("Enter number of cart: ");
        var numOfCarts = Convert.ToInt32(Console.ReadLine());

        Console.Write("Enter number of items: ");
        var numOfItems = Convert.ToInt32(Console.ReadLine());
        RunTasks(numOfCarts, numOfItems).Wait();
    }
}

public static Task RunTasks(int numOfCarts, int numOfItems)
{
    Task[] tasks = new Task[numOfCarts];
    for (var i = 0; i < numOfCarts; i++)
    {
        tasks[i] = Task.Run(() =>
        {
            var color = (ConsoleColor) new Random().Next(0, 15);
            for (var q = 0; q < numOfItems; q++) {
                Console.ForegroundColor = color;
                Console.WriteLine("Cart {0} : {1}", i, q);
            }
        });
    }

    return Task.WhenAll(tasks);
}    
  • RunTasks starts up many Tasks and returns a task which will complete when all subtasks are complete.
  • Main will start RunTasks and block main thread until RunTasks finishes.

At the same time, you can make await Task.WhenAll in RunTasks and then await RunTasks() in Main, but it doesn't make much sense - your main thread is always busy and will infinitely do one job (which is RunTasks).

Upvotes: 1

Related Questions