user829174
user829174

Reputation: 6362

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

Upvotes: 4

Views: 2917

Answers (2)

eandersson
eandersson

Reputation: 26362

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.

Upvotes: 12

kenny
kenny

Reputation: 22414

Try this.

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

Upvotes: 2

Related Questions