为什么以下的
该程序开始执行count()方法,但是在完成之前就退出了。使用await task语句时,我希望它等待所有循环(0、1、2、3、4)完成count()方法后再退出。但是我只得到了“count loop: 0”。但是它确实在经过所有的callCount()。好像await task没有起到任何作用。我希望count()和callCount()都异步运行,并在完成后返回主函数。
async
和 await
没有起作用?我正在尝试学习并理解我的代码哪里出了问题。class Program
{
static void Main(string[] args)
{
callCount();
}
static void count()
{
for (int i = 0; i < 5; i++)
{
System.Threading.Thread.Sleep(2000);
Console.WriteLine("count loop: " + i);
}
}
static async void callCount()
{
Task task = new Task(count);
task.Start();
for (int i = 0; i < 3; i++)
{
System.Threading.Thread.Sleep(4000);
Console.WriteLine("Writing from callCount loop: " + i);
}
Console.WriteLine("just before await");
await task;
Console.WriteLine("callCount completed");
}
}
该程序开始执行count()方法,但是在完成之前就退出了。使用await task语句时,我希望它等待所有循环(0、1、2、3、4)完成count()方法后再退出。但是我只得到了“count loop: 0”。但是它确实在经过所有的callCount()。好像await task没有起到任何作用。我希望count()和callCount()都异步运行,并在完成后返回主函数。
await
等待callCount
的结果,那么你认为会发生什么? - DavidGcallCount
中的循环总时间比count
中的循环长。在.Net控制台应用程序中,Program
和Main
可以是私有的,没有问题。@Arturo Menchaca在下面给出了正确的答案。 - ErgwunMain
中使用async void
和阻塞主线程以防止应用程序退出之外,您还应该永远不要使用Task
构造函数或Task.Start
(请改用Task.Run
)。 - Stephen ClearyTask task = new Task(count); task.Start();
替换为Task task = Task.Run(() => count());
,它应该与原始代码的行为相同。 - Stephen Cleary