Search code examples
c#parallel-processingtasktask-parallel-libraryparallel.foreach

Why can't I get output from Parallel.ForEach in the code below?


public static class Program
{
    private static void Main(string[] args)
    {
        List<string> urls = new List<string> {
            "https://www.microsoft.com",
            "https://www.google.com",
            "https://www.amazon.com"
        };

        List<string> Results = new List<string>();
        Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " 1");

        Task.Run(() =>
        {
            Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " 2");
            HttpClient client = new HttpClient();
            var p = Parallel.ForEach<string>(urls, (url) =>
            {
                Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " 3");
                Console.WriteLine(url);
                var content = client.GetStringAsync(url).Result;
                Results.Add(url + " " + content.Length);
                Console.WriteLine(url + " " + content.Length);
            });
        });

        Console.WriteLine("Main program");
    }
}

When I run the code, I get an output like the one below.

1 1
Main Program

Why is there no output from the places I marked as 2 or 3?

So there is no output from Console.WriteLine in Task.Run() and Parallel.ForEach().

I want to print all thread ids.


Solution

  • The Task.Run method returns a Task object, that represents the completion of the asynchronous operation. You have to wait for the operation to complete, otherwise the main thread will terminate, and shortly after the process will terminate too after aborting all background threads. The simplest way to wait the task to complete is by calling the Wait method:

    Task.Run(() =>
    {
        //...
    }).Wait();