Why my task work only once?

2019-08-08 14:37发布

I want to print every 2 sec number but and in the end i get only 0 what i need to do to get this every 2 sec?

result:

    0
    1
    .
    .
    49

  private static void Main(string[] args) {
    Send();
  }

  public static async Task Send() {
    for (int i = 0; i < 50; i++) {
        Console.WriteLine(i);
        await Task.Delay(2000);
    }
  }

3条回答
forever°为你锁心
2楼-- · 2019-08-08 15:01

Building on Josephs answer, but in a more general "How to do asynchronous console apps"-way

Using asynchronous code in console apps can be a bit tricky. I generally use a substitute MainAsync method that the original Main() calls and makes a blocking wait on.

Here comes an example of how it could be done:

class Program
{
    static void Main(string[] args)
    {
        Task mainTask = MainAsync(args);
        mainTask.Wait();
        // Instead of writing more code here, use the MainAsync-method as your new Main()
    }

    static async Task MainAsync(string[] args)
    {
        await Send();
        Console.ReadLine();
    }

    public static async Task Send()
    {
        for (int i = 0; i < 50; i++)
        {
            Console.WriteLine(i);
            await Task.Delay(2000);
        }
    }
}
查看更多
等我变得足够好
3楼-- · 2019-08-08 15:12

well, simply because your Main method won't wait for the send method to finish and you can't use the await keyword in order for that to happened since the compiler won't allow an async Main, in that case you could simple use a Task.Run

 private static void Main(string[] args)
    {
        Task.Run(async () =>
        {
            await Send();
        }).Wait();
    }

    public static async Task Send()
    {
        for (int i = 0; i < 50; i++)
        {
            Console.WriteLine(i);
            await Task.Delay(2000);
        }
    }
查看更多
再贱就再见
4楼-- · 2019-08-08 15:16

What you are missing is a Console.ReadLine() call, to halt the console from exiting the program before your task gets executed. Tested the code below and it works.

    private static void Main(string[] args)
    {
        Send();
        Console.ReadLine();
    }

    public static async Task Send()
    {
        for (int i = 0; i < 50; i++)
        {
            Console.WriteLine(i);
            await Task.Delay(2000);
        }
    }
查看更多
登录 后发表回答