El-*_*rar 1 .net c# console-application async-await
此程序不会以正确的顺序打印输出.
public static void Main(string[] args)
{
new Program().Start();
}
public async void Start()
{
int num1 = await GetNumber();
int num2 = await GetNumber();
int num3 = await GetNumber();
Console.WriteLine("Wait...");
Console.ReadKey();
}
public static async Task<int> GetNumber()
{
System.Threading.Thread.Sleep(4000);
Console.WriteLine("Hello");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它输出:
--------wait 4Seconds
--------print Hello
--------wait 4Seconds
--------print Hello
--------wait 4Seconds
--------print Hello
--------print wait....
Run Code Online (Sandbox Code Playgroud)
它应该输出
--------print wait....
--------wait 4Seconds
--------print Hello
--------print Hello
--------print Hello
Run Code Online (Sandbox Code Playgroud)
使用
Await Task.Delay(Timespan.FromMilliSeconds (4000))
Run Code Online (Sandbox Code Playgroud)
而不是Thread.Sleep.
完全成功的例子.
using System;
using System.Threading.Tasks;
namespace Brad
{
public class Program
{
public static void Main(string[] args)
{
var task = new Program().Start();
Console.WriteLine("Wait...");
// You have to put a synchronous Wait() here because
// Main cannot be declared as async
task.Wait();
}
public async Task Start()
{
int num1 = await GetNumber();
int num2 = await GetNumber();
int num3 = await GetNumber();
Console.WriteLine("Finished");
}
public static async Task<int> GetNumber()
{
await Task.Delay(TimeSpan.FromMilliseconds(400));
Console.WriteLine("Hello");
return 0;
}
}
}
Run Code Online (Sandbox Code Playgroud)
你可以看到它在这里运行
https://dotnetfiddle.net/KHJaDZ
或者您可能希望并行运行任务而不是一个接一个地运行.你可以试试
using System;
using System.Threading.Tasks;
namespace Brad
{
public class Program
{
public static void Main(string[] args)
{
var task = new Program().Start();
Console.WriteLine("Wait...");
// You have to put a synchronous Wait() here because
// Main cannot be declared as async
task.Wait();
}
public async Task Start()
{
var task1 = GetNumber();
var task2 = GetNumber();
var task3 = GetNumber();
// This runs the tasks in parallel
await Task.WhenAll(task1, task2, task3);
Console.WriteLine("Finished");
}
public static async Task<int> GetNumber()
{
await Task.Delay(TimeSpan.FromMilliseconds(400));
Console.WriteLine("Hello");
return 0;
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是在这里运行.
https://dotnetfiddle.net/kVk77Z