using System;
using System.Threading;
using System.Threading.Tasks;
namespace application
{
public class Files
{
public static Task<string> runTask()
{
return Task.Run(() =>
{
Thread.Sleep(2000);
return "Hello World!";
});
}
public static async void Hello()
{
string result = await runTask();
Console.WriteLine(result);
Console.WriteLine("Execution Ended!");
}
public static void Main(string[] args)
{
Hello();
Console.WriteLine("The Async Code Is Running Above!");
}
};
};
上面的C#代码只是打印“异步代码正在上面运行!” 之后什么都没发生。
我怎样才能按以下顺序打印这些东西(以及我哪里出错了):
“上面运行的是异步代码!” “你好,世界!” “行刑结束!”
谢谢!
避免使用void异步方法,尝试始终返回任务。 查看这篇文章以获得更多细节异步等待时返回任务vs void
class Files
{
static void Main(string[] args)
{
Task t = Hello();
Console.WriteLine("The Async Code Is Running Above!");
//Wait for the task to complete
//Dont use this code in UI applications which will cause blocking
t.Wait();
//keep the application open
Console.ReadLine();
}
public static Task<string> runTask()
{
return Task.Run(async () =>
{
await Task.Delay(2000);
return "Hello World!";
});
}
public static async Task Hello()
{
string result = await runTask();
Console.WriteLine(result);
Console.WriteLine("Execution Ended!");
}
}
你的问题主要有两点。 首先,不要使用thread.sleep(2000);
在异步方法中使用task.delay
。 其次,您还可以使main
方法async
,并返回一个task
以获得预期的行为(从C#7.1开始是可能的)
public static Task<string> runTask()
{
return Task.Run(async () =>
{
await Task.Delay(2000);
return "Hello World!";
});
}
public static async Task Hello()
{
string result = await runTask();
Console.WriteLine(result);
Console.WriteLine("Execution Ended!");
}
static async Task Main()
{
await Hello();
Console.WriteLine("The Async Code Is Running Above!");
}