[英]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. 在上面的代码中运行时,我编写了一个从0到1000000的循环,循环从未完成。 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. 控制台线程实际上将在循环完成之前退出,因为
Task.Run
与控制台应用程序的线程异步运行任务。
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
或者您通过将所有任务添加到列表中并使用
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 . Task
正在后台线程中运行。 When the main thread stops all tasks are terminated. 当主线程停止时,所有任务都将终止。 If you add
Task.WaitAll
after your code, it will work. 如果在代码后添加
Task.WaitAll
,它将可以正常工作。
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: 以下内容在具有Mono的OS X上完美运行:
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.