入口点不能用“async"修饰符标记 [英] An entry point cannot be marked with the 'async' modifier

查看:19
本文介绍了入口点不能用“async"修饰符标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从这个 链接.但是当我编译这段代码时,我得到一个入口点不能用异步"修饰符标记.如何使此代码可编译?

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("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. 
        //    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
}

推荐答案

错误信息完全正确:Main() 方法不能是 async,因为当 Main() 返回,应用程序通常结束.

The error message is exactly right: the Main() method cannot be async, because when Main() returns, the application usually ends.

如果你想制作一个使用 async 的控制台应用程序,一个简单的解决方案是创建一个 async 版本的 Main() 和从真正的 Main() 同步Wait():

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
}

这是混合awaitWait() 是一个好主意的罕见情况之一,您通常不应该这样做.

This is one of the rare cases where mixing await and Wait() is a good idea, you shouldn't usually do that.

更新:异步主在 C# 7.1 中支持.

这篇关于入口点不能用“async"修饰符标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆