0

I'm following this tutorial on Udemy. The instructor has put this simple code on screen. And it's working on the instructor screen.

 class Program
{
    static void Main(string[] args)
    {
        Task.Run(() => Print());
        Task.Factory.StartNew(() => Print());

        //Print();
    }

    private static void Print()
    {
        for (int i = 0; i < 100; i++)
        {
            Console.WriteLine(i);
        }
    }
}

Nothing is happening for me. I don't see the numbers on the screen. Am I missing something? However, this code works, i.e. if I add the wait() method.

var t = Task.Run(() => Print());
t.Wait();

Thanks for helping

Richard77
  • 20,343
  • 46
  • 150
  • 252
  • 1
    The program exits first..? Replace the Wait with a `Thread.Sleep(Timespan.FromSeconds(20))` and compare.. If it’s not “fire and *really* forget”, the result generally must be waited. – user2864740 Nov 09 '20 at 05:25
  • Your link doesn't work by the way, since it requires login. – Evk Nov 09 '20 at 07:07
  • 1
    Add `Console.ReadKey()` at the end of `Main` method. – Sinatr Nov 09 '20 at 08:12
  • Does this answer your question? [Why is the console window closing immediately once displayed my output?](https://stackoverflow.com/questions/8868338/why-is-the-console-window-closing-immediately-once-displayed-my-output) – Sinatr Nov 09 '20 at 08:14
  • @Sinatr I just notice that there's a `Console.ReadKey()` line that I overlooked because I didn't know it has any impact on the way the code works. Sorry, I'm in the early stage of understanding how asynchronous programming. The author didn't explain that. – Richard77 Nov 09 '20 at 15:34
  • @user2864740 it was confusing to me because `await` is normally next to the operation supposed to be asynchronous. I didn't know that the `Console.ReadKey()` would have the same effect. I googled like crazy but all I could find is that I had to add `wait()` for it to work. I've a long way to go with asynchronous programming. – Richard77 Nov 09 '20 at 15:41

1 Answers1

1

Your Main method returns and the program exits before the task started running.

Adding .Wait prevents this, since the Main method will now wait for the task to complete. By doing this, you however lose any benefit of using a Task in the first place, since just calling Print inside Main would do the same.

Matthias247
  • 9,836
  • 1
  • 20
  • 29
  • 1
    _"By doing this, you however lose any benefit of using a Task in the first place"_ - In OP's example, that's true, but that's not generally 100% true since you could do other stuff between the firing off of the task and the wait for it to complete. – ProgrammingLlama Nov 09 '20 at 05:44