C# 任务未完成(命令提示符中无结果)
C# Task not completing (no results in command prompt)
using System;
using System.Threading.Tasks;
namespace _1._8_Starting_A_New_Task
{
public static class Program
{
public static void Main()
{
Task t = new Task(() =>
{
for (int x = 0; x < 100; x++)
{
Console.Write('*');
}
});
t.Wait();
}
}
}
- 此应用程序编译并运行显示空白屏幕(等待任务完成)
- 任务处于等待状态
- 没有输出 displayed/written 到控制台
- 为什么不呢?
- 应用程序永久保持 "wait" 状态
- 为什么?
- 代码目标:启动新任务,等待任务完成,退出应用程序
因为你从来没有启动过Task
。使用 Task
constructor requires you to call Task.Start
on the returned task. This is why it's recommended to use Task.Run
代替,其中 returns 一个 "Hot task" (已经开始的任务):
文档:
Rather than calling this constructor, the most common way to
instantiate a Task object and launch a task is by calling the static
Task.Run(Action)
or TaskFactory.StartNew(Action)
method. The only
advantage offered by this constructor is that it allows object
instantiation to be separated from task invocation.
所以代码应该是:
public static void Main()
{
Task t = Task.Run(() =>
{
for (int x = 0; x < 100; x++)
{
Console.Write('*');
}
});
t.Wait();
}
using System;
using System.Threading.Tasks;
namespace _1._8_Starting_A_New_Task
{
public static class Program
{
public static void Main()
{
Task t = new Task(() =>
{
for (int x = 0; x < 100; x++)
{
Console.Write('*');
}
});
t.Wait();
}
}
}
- 此应用程序编译并运行显示空白屏幕(等待任务完成)
- 任务处于等待状态
- 没有输出 displayed/written 到控制台
- 为什么不呢?
- 应用程序永久保持 "wait" 状态
- 为什么?
- 代码目标:启动新任务,等待任务完成,退出应用程序
因为你从来没有启动过Task
。使用 Task
constructor requires you to call Task.Start
on the returned task. This is why it's recommended to use Task.Run
代替,其中 returns 一个 "Hot task" (已经开始的任务):
文档:
Rather than calling this constructor, the most common way to instantiate a Task object and launch a task is by calling the static
Task.Run(Action)
orTaskFactory.StartNew(Action)
method. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation.
所以代码应该是:
public static void Main()
{
Task t = Task.Run(() =>
{
for (int x = 0; x < 100; x++)
{
Console.Write('*');
}
});
t.Wait();
}