我复制下面code从this link.But当我编译这个code我得到一个切入点不能打上异步修改即可。我怎样才能让这个code编译?
类节目{ 异步静态无效的主要(字串[] args) { 任务<串GT; getWebPageTask = GetWebPageAsync(msdn.microsoft); 的Debug.WriteLine(在startButton_Click的await之前); 字符串webText =等待getWebPageTask; 的Debug.WriteLine(字符收到:+ webText.Length.ToString()); } 私有静态异步任务<串GT; GetWebPageAsync(字符串URL) { //开始一个异步任务。 任务<串GT; getStringTask =(新的HttpClient())GetStringAsync(URL)。 //等待任务。这是发生了什么: // 1.执行立即返回到调用方法,返回 //从previous语句创建的任务不同的任务。 //这个方法执行暂停。 // 2.在previous语句完成,创建任务 //从GetStringAsync方法结果由等待产生 //声明,并继续执行该方法中。 的Debug.WriteLine(在GetWebPageAsync的await之前); 字符串webText =等待getStringTask; 的Debug.WriteLine(以GetWebPageAsync后AWAIT); 返回webText; } //输出: //在GetWebPageAsync之前的await //在startButton_Click之前的await //在GetWebPageAsync后的await //人物好评:44306}解决方案
该错误信息是完全正确的:的Main()方法不能是异步,因为当的Main()的回报,应用程序通常结束。
如果你想使用一个控制台应用程序异步,一个简单的解决方案是创建一个异步版本的的Main()并同步等待()上,从实际的Main():
静态无效的主要(){ MainAsync()等待()。}静态异步任务MainAsync(){ //你的异步code在这里}这就是混合的罕见的情况下有一个等待和等待()是一个好主意,你不应该T通常做到这一点。
更新:异步主要是的目前预期,使之成为C#7.0 。
I copied below code from this link.But when I am compiling this code I am getting an entry point cannot be marked with the 'async' modifier. How can I make this code compilable?
class Program { static async void Main(string[] args) { Task<string> getWebPageTask = GetWebPageAsync("msdn.microsoft"); 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. // Execution in this method is suspended. // 2. When the task created in the previous statement completes, the // result from the GetStringAsync method is produced by the Await // statement, and execution continues within this method. Debug.WriteLine("In GetWebPageAsync before await"); string webText = await getStringTask; Debug.WriteLine("In GetWebPageAsync after await"); return webText; } // Output: // In GetWebPageAsync before await // In startButton_Click before await // In GetWebPageAsync after await // Characters received: 44306 }解决方案
The error message is exactly right: the Main() method cannot be async, because when Main() returns, the application usually ends.
If you want to make a console application that uses async, a simple solution is to create an async version of Main() and synchronously Wait() on that from the real Main():
static void Main() { MainAsync().Wait(); } static async Task MainAsync() { // your async code here }This is one of the rare cases where mixing await and Wait() is a good idea, you shouldn't usually do that.
Update: Async Main is currently expected to make it into C# 7.0.
更多推荐
入口点不能被打上了“异步”修饰符
发布评论