Task.Factory.StartNew () doesn't work for me

I wrote this small application. for some reason I cannot print "Hello from the thread" when I run this program. however, if I debug it and put a breakpoint in the Do () method, it prints.

Any ideas?

using System; using System.Threading.Tasks; namespace ConsoleApplication3 { internal class Program { private static void Main(string[] args) { Task.Factory.StartNew(Do); } private static void Do() { Console.WriteLine("Hello from a thread"); } } } 
+4
source share
2 answers

Are you sure that the program simply does not close before you can see the result? Because it works great for me.

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { private static void Main(string[] args) { Task.Factory.StartNew(Do); Console.Read(); } private static void Do() { Console.WriteLine("Hello from a thread"); } } } 

Edit: Added a comment that I wrote in response to this, including my reasoning about why the text was not printed.

This is either because the application closes before the stream has the ability to display a string on the screen. It is also possible that you simply do not see it, because it closes right away. In any case, the reason it worked with the breakpoint is because you save the application longer.

+11
source

Try it.

 using System; using System.Threading.Tasks; namespace ConsoleApplication3 { internal class Program { static void Main(string[] args) { Task.Factory.StartNew(Do); Console.ReadKey(); } static void Do() { Console.WriteLine("Hello from a thread"); } } } 
+2
source

Source: https://habr.com/ru/post/1389903/


All Articles