简体   繁体   中英

C# Tasks in a loop never ends

Consider this code:

for (int i = 0; i < 1000000; i++)
{
    int i1 = i;
    Task.Run(() => Console.WriteLine(i1));
}

I write a loop from 0 to 1000000 when running above code,loop never completes. Why this loop never completes?

Thats because you never wait for your task to complete. I expect you run this within a console application. The console thread will actually exit before your loop completes because Task.Run runs the task asynchronously to the thread of your console application.

Either you wait for the task to complete

        for (int i = 0; i < 1000000; i++)
        {
            int i1 = i;
            Task.Run(() => Console.WriteLine(i1)).Wait();
        }

Or you keep your console window open

    static void Main(string[] args)
    {
        for (int i = 0; i < 1000000; i++)
        {
            int i1 = i;
            Task.Run(() => Console.WriteLine(i1));
        }

        Console.ReadKey();
    }

Or you wait for all tasks to complete by adding them to a list and use Task.WaitAll

        var tasks = new List<Task>();
        for (int i = 0; i < 1000000; i++)
        {
            int i1 = i;
            tasks.Add(Task.Run(() => Console.WriteLine(i1)));
        }

        Task.WaitAll(tasks.ToArray());

Task is running in background thread . When the main thread stops all tasks are terminated. If you add Task.WaitAll after your code, it will work.

List<Task> tasks = new List<Task>();
for (int i = 0; i < 10000; i++)
{
    int i1 = i;
    tasks.Add(Task.Run(() => Console.WriteLine(i1)));
}

Task.WaitAll(tasks.ToArray());

The following works perfectly on my OS X with Mono:

using System.Threading.Tasks;
using System;

public class Test
{
    public static int Main(string[] args)
    {
        for (int i = 0; i < 1000000; i++)
        {
            int i1 = i;
            Task.Run(() => Console.WriteLine(i1));
        }
        return 0;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM