Why my task work only once?

半世苍凉 提交于 2019-12-24 12:02:41

问题


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);
    }
  }

回答1:


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);
        }
    }



回答2:


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);
        }
    }



回答3:


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);
        }
    }
}


来源:https://stackoverflow.com/questions/34376226/why-my-task-work-only-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!