Hello. Please tell me why in this code the output is a blank screen.

class a { static void Meth(int x, int y) { Console.WriteLine(x + y); } static void Main() { Task t = new Task(() => Meth(5, 4)); t.Start(); } } 

What especially surprised me was that through step-by-step debugging, the compiler does not go into the Meth method at all. Why

  • Are you sure that the screen is empty? Or that you run this particular code and not some other one? I have this code works fine, the screen displays 9, as expected. I also note that your Main method ends immediately, immediately closing the console, that is, physically difficult to see the result - DreamChild
  • And really, I ran it 5 times, 3 of them displays 9, and 2 is empty. It seems that the exit from the Main method occurs earlier. But then why in step-by-step debugging, the compiler does not even go into the Meth method. Now launched 10 times and all the time is empty - Polyakov Sergey

3 answers 3

The point is this. t.Start runs the Task on the current TaskScheduler . Because you run from a non-UI thread, you have a default TaskScheduler running in it - the one that executes the Task in the thread pool.

Then, what happens immediately after starting the task? Main ends and the program dies before it completes the task. The task goes to the thread pool, but the program has time to complete before starting the task.

Threads of the thread pool do not suspend the completion of the program, if the Main function ends, then the entire program ends.

Try t.Wait() after t.Start() .

    This code does not have time to execute, as the program exits.

    Try this:

     class Program { static void Meth(int x, int y) { Console.WriteLine(x + y); } static void Main() { Task task = new Task(() => Meth(5, 4)); task.Start(); task.Wait(); //Console.ReadKey(); } } 

      Sometimes a task (rather a ContinueWith task) is well executed on the same thread as the user interface.

       class Program { static void Meth(int x, int y) { Console.WriteLine(x + y); } static void Main() { SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); Task.Factory .StartNew( () => Meth(5, 4) ,CancellationToken.None ,TaskCreationOptions.None ,TaskScheduler.FromCurrentSynchronizationContext() ); //Console.ReadKey(); } } 

      When I did this in WPF, I did not need to install SetSynchronizationContext .