为什么以下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");
}
}
Run Code Online (Sandbox Code Playgroud)
程序将启动count()方法,但在没有完成的情况下退出.随着等待任务; 语句我希望它在退出之前等待完成count()方法的所有循环(0,1,2,3,4).我只得到"计数循环:0".但是它经历了所有的callCount().它就像等待任务一样没有做任何事情.我希望count()和callCount()都异步运行并在完成时返回main.
Art*_*aca 14
当您执行一个async方法时,它会同步开始运行,直到它到达一个await语句,然后其余的代码异步执行,并且执行返回给调用者.
在您的代码callCount()开始同步运行await task,然后返回到Main()方法,并且由于您没有等待方法完成,程序结束而没有方法count()可以完成.
您可以通过更改返回类型看所需的行为Task,并呼吁Wait()在Main()方法.
static void Main(string[] args)
{
callCount().Wait();
}
static void count()
{
for (int i = 0; i < 5; i++)
{
System.Threading.Thread.Sleep(2000);
Console.WriteLine("count loop: " + i);
}
}
static async Task callCount()
{
Task task = new Task(count);
task.Start();
for (int i = 0; i < 3; i++)
{
System.Threading.Thread.Sleep(1000);
Console.WriteLine("Writing from callCount loop: " + i);
}
Console.WriteLine("just before await");
await task;
Console.WriteLine("callCount completed");
}
Run Code Online (Sandbox Code Playgroud)
编辑: 这是你的代码执行方式:
(为了更好地理解,让更改CallCount()返回类型Task)
Main()方法开头.CallCount() 方法被调用.Count(),并行创建一个运行方法的新线程.await task;到达.这是async-await模式发挥作用的时候.await不一样Wait(),它在任务完成之前不阻塞当前线程,但是将执行控制返回给Main()方法,并且在任务完成后将执行所有剩余指令CallCount()(在这种情况下Console.WriteLine("callCount completed");).Main(),调用CallCount()返回a Task(使用剩余的指令CallCount()和原始任务)并继续执行.Main()将继续完成程序和正在销毁的任务.Wait()(如果CallCount()是无效的,你不要有一个任务等待)你让任务完成,持有Main()的Count()执行和"callCount完成"正在打印.如果你想在CallCount()没有返回Main()方法的情况下等待计数任务完成,请调用task.Wait();,所有程序都会等待Count(),但这不是await会做什么的.
此链接详细说明了async-await模式.
希望您的代码工作流程图能够帮助您.