0 votes
by (2.5k points)

I've seen two different ways to spin up tasks/threads in C#. There is : 

Task.Run(() => Console.WriteLine("Hello World!"));

But there is also : 

Task.Factory.StartNew(() => Console.WriteLine("Hello World!"));

What's the difference? Both seem to work fine. 

1 Answer

0 votes
by (2.5k points)

The interesting thing is that Task.Run is actually shorthand for : 

Task.Factory.StartNew(() => Console.Writeline("Hello World!"),

You can see this within Microsoft's own source code here : https://github.com/microsoft/referencesource/blob/master/mscorlib/system/threading/Tasks/Task.cs#L5614

public static Task Run(Action action)
	return Task.InternalStartNew(null, action, null, default(CancellationToken), TaskScheduler.Default,
		TaskCreationOptions.DenyChildAttach, InternalTaskOptions.None, ref stackMark);

So essentially, you should be using Task.Run in 99% of cases. It sets up running Task.Factory.StartNew with the default parameters that will serve you well in almost all use cases. 

Welcome to .NET Q&A, where you can ask questions and receive answers from other members of the community.