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!");
}
};
};
Run Code Online (Sandbox Code Playgroud)
上面的 C# 代码只打印“The Async Code Is Running Below!” 之后什么也没有发生。
我怎样才能按以下顺序打印内容(以及我出错的地方):
“上面运行的是异步代码!” “你好世界!” “行刑结束!”
谢谢你!
你的问题有两个要点。首先,不要使用Thread.Sleep内部异步方法,Task.Delay而是使用。其次,您也可以创建Main方法async并返回 aTask以获得预期的行为(可以从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!");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
868 次 |
| 最近记录: |