1

I am a beginner and don't know much about this subject. But apparently, all these statements allows the application to run its tasks in background threads. This is really confusing. Which ones should be used/not used or preferred?

Task t = new Task( () => doSomeWork() );
t.Start();

And

Task t = Task.Run( () => doSomeWork1() );

And

Task t = Task.Factory.StartNew( () => doSomeWork2() );

And

Thread t = new Thread(new ThreadStart( doSomeWork3 ));
t.Start();

And probably there are even more like BackgroundWorker. Which and when these should be used?

Mark S
  • 347
  • 1
  • 4
  • 12
  • the different forms of `Task` are discussed clearly on the documentation at https://msdn.microsoft.com/en-us/library/system.threading.tasks.task%28v=vs.110%29.aspx. Is there something specific there that isn't clear? – Claies Jun 18 '16 at 20:59
  • 1
    Very broad question. "There are a lot of features in C#. When do I use each one?" – Matt Rowland Jun 18 '16 at 21:00

1 Answers1

2

Task.Run is equivalent to creating a task and then running Start. These kinds of tasks run on the thread pool. Usually, for a background operation in modern C# .NET this is what you want.

Using Task.Factory.StartNew is something you will see in legacy code, but Microsoft recommends using Task.Run for modern compute bound tasks.

Manually creating a thread is a lower level operation and bypasses the thread pool. Usually this is not what you want either as the thread pool will take care of things like not creating too many threads, and also allows you to write async code, have continuations, pass synchronization contexts, etc.

Usually you will be best advised to use Task.Run.

bodangly
  • 2,473
  • 17
  • 28