我是使用async修饰符进行异步编程的新手.我试图弄清楚如何确保我Main的控制台应用程序的方法实际上异步运行.
class Program
{
static void Main(string[] args)
{
Bootstrapper bs = new Bootstrapper();
var list = bs.GetList();
}
}
public class Bootstrapper {
public async Task<List<TvChannel>> GetList()
{
GetPrograms pro = new GetPrograms();
return await pro.DownloadTvChannels();
}
}
Run Code Online (Sandbox Code Playgroud)
我知道这不是从"顶部"异步运行的.由于无法async在Main方法上指定修饰符,如何在main异步中运行代码?
我从这个 链接复制下面的代码.但是当我编译这段代码时,我得到的入口点不能用'async'修饰符标记.如何使这段代码可编辑?
class Program
{
static async void Main(string[] args)
{
Task<string> getWebPageTask = GetWebPageAsync("http://msdn.microsoft.com");
Debug.WriteLine("In startButton_Click before await");
string webText = await getWebPageTask;
Debug.WriteLine("Characters received: " + webText.Length.ToString());
}
private static async Task<string> GetWebPageAsync(string url)
{
// Start an async task.
Task<string> getStringTask = (new HttpClient()).GetStringAsync(url);
// Await the task. This is what happens:
// 1. Execution immediately returns to the calling method, returning a
// different task from the task created in the previous statement. …Run Code Online (Sandbox Code Playgroud)