Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Task.Factory.StartNew() not working for me

I wrote this small application. for some reason i am not being able to print "Hello from a thread" when i run this program. however if i debug it and put a breakpoint inside Do() method, it does print.

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");
        }
    }
}
like image 702
user829174 Avatar asked Dec 10 '22 03:12

user829174


1 Answers

Are you sure that the program simply isn't closing before you can see the output? Because this works fine 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 the comment I wrote in response to this, including my reasoning to why the text wasn't printed.

Its either because the application closes down before the thread has the possibility of outputting the string to the screen. It's also possible that you simply cant see it because it closes straight away. Either way the reason it worked with the breakpoint is because you keep the application alive longer.

like image 119
eandersson Avatar answered Dec 25 '22 15:12

eandersson