无法使用"async"修饰符标记入口点

44 c# async-await c#-5.0

我从这个 链接复制下面的代码.但是当我编译这段代码时,我得到的入口点不能用'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. 
        //    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
}
Run Code Online (Sandbox Code Playgroud)

svi*_*ick 76

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

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

static void Main()
{
    MainAsync().Wait();
}

static async Task MainAsync()
{
    // your async code here
}
Run Code Online (Sandbox Code Playgroud)

这是其中混合少见的情况awaitWait()是一个好主意,你通常不应这样做.

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

  • @bilalfazlani会有什么样的结果?`Main()`通常不会返回任何内容.在任何情况下,如果你有一个`Task <T>`(即带有结果的`Task`),你可以使用`Result`而不是`Wait()`. (7认同)

Rom*_*och 11

从C#7.1开始,有4个新的签名Main方法允许它async(,源2,源3):

public static Task Main();
public static Task<int> Main();
public static Task Main(string[] args);
public static Task<int> Main(string[] args);
Run Code Online (Sandbox Code Playgroud)

您可以Main使用async关键字标记您的方法并await在内部使用Main:

static async Task 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()); 
}
Run Code Online (Sandbox Code Playgroud)

Visual Studio 2017 15.3中提供了C#7.1.

  • 作为脚注,您需要更改项目构建设置以使用特定的次要 C# 版本,否则它将默认为 C#7.0。这将使您能够在 `Main` 上使用 `async` 关键字。 (2认同)