gal
gal

Reputation: 49

Why my task work only once?

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

Upvotes: 1

Views: 266

Answers (3)

Shazi
Shazi

Reputation: 1569

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

Upvotes: 0

Toni Kostelac
Toni Kostelac

Reputation: 361

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

Upvotes: 0

user5699258
user5699258

Reputation:

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

Upvotes: 1

Related Questions