編譯器錯誤 CS4009

'Type.Method':進入點不能以 async 修飾詞標記。

您無法在應用程式進入點 (通常是 Main 方法) 中使用 async 關鍵字。

重要

從 C# 7.1 開始,Main 方法可以有 async 修飾詞。 如需詳細資訊,請參閱 Async Main 傳回值。 如需如何選取 C# 語言版本的資訊,請參閱選取 C# 語言版本一文。

範例

下列範例會產生 CS4009:

using System;
using System.Threading.Tasks;

public class Example
{
    public static async void Main()
    {
        Console.WriteLine("About to wait two seconds");
        await WaitTwoSeconds();
        Console.WriteLine("About to exit the program");
    }

    private static async Task WaitTwoSeconds()
    {
        await Task.Delay(2000);
        Console.WriteLine("Returning from an asynchronous method");
    }
}

更正這個錯誤

將專案所使用的 C# 語言版本更新為 7.1 或更高版本。

如果您使用 C# 7.0 或更低版本,請從應用程式進入點的簽章中移除 async 關鍵字。 此外,請移除您在應用程式進入點中用來等候非同步方法的任何 await 關鍵字。

不過,在進入點繼續執行之前,您仍然需要等候非同步方法完成。 否則,編譯會產生編譯器警告 CS4014,而且應用程式會在非同步作業完成之前終止。 下列範例說明此問題:

using System;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
       Console.WriteLine("About to wait two seconds");
       WaitTwoSeconds();
       Console.WriteLine("About to exit the program");
   }

   private static async Task WaitTwoSeconds()
   {
      await Task.Delay(2000);
      Console.WriteLine("Returning from an asynchronous method");
   }
}
// The example displays the following output:
//       About to wait two seconds
//       About to exit the program

若要等候傳回 Task 的方法,請呼叫其 Wait 方法,如下列範例所示:

using System;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
       Console.WriteLine("About to wait two seconds");
       WaitTwoSeconds().Wait();
       Console.WriteLine("About to exit the program");
   }

   private static async Task WaitTwoSeconds()
   {
      await Task.Delay(2000);
      Console.WriteLine("Returning from an asynchronous method");
   }
}
// The example displays the following output:
//       About to wait two seconds
//       Returning from an asynchronous method
//       About to exit the program

若要等候傳回 Task<TResult> 的方法,請擷取其 Result 屬性的值,如下列範例所示:

using System;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
       Console.WriteLine("About to wait two seconds");
       int value = WaitTwoSeconds().Result;
       Console.WriteLine($"Value returned from the async operation: {value}");
       Console.WriteLine("About to exit the program");
   }

   private static async Task<int> WaitTwoSeconds()
   {
      await Task.Delay(2000);
      Console.WriteLine("Returning from an asynchronous method");
      return 100;
   }
}
// The example displays the following output:
//       About to wait two seconds
//       Returning from an asynchronous method
//       Value returned from the async operation: 100
//       About to exit the program

另請參閱