51

このリンクから以下のコードをコピーしました。 しかし、このコードをコンパイルしているときに、エントリ ポイントを「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
}
4

5 に答える 5

1

リンクの例とあなたのコードの違いは、Main()メソッドをasync修飾子でマークしようとしていることです-これは許可されておらず、エラーはまさにそれを示しています-Main()メソッドはアプリケーションへの「エントリポイント」です(アプリケーションの起動時に実行されるメソッドです) async

于 2013-05-23T11:03:01.417 に答える