7 ways to start a Task in .NET C#

New threads can be started using the Task Programming Library in .NET in – at last – 5 different ways.

You’ll first need to add the following using statement:

using System.Threading.Tasks;

The most direct way

Task.Factory.StartNew(() => {Console.WriteLine("Hello Task library!"); });

Using Action

Task task = new Task(new Action(PrintMessage));

…where PrintMessage is a method:

private void PrintMessage()
    Console.WriteLine("Hello Task library!");

Using a delegate

Task task = new Task(delegate { PrintMessage(); });

Lambda and named method

Task task = new Task( () => PrintMessage() );

Lambda and anonymous method

Task task = new Task( () => { PrintMessage(); } );

Using Task.Run in .NET4.5

public async Task DoWork()
	await Task.Run(() => PrintMessage());

Using Task.FromResult in .NET4.5 to return a result from a Task

public async Task DoWork()
	int res = await Task.FromResult<int>(GetSum(4, 5));	

private int GetSum(int a, int b)
	return a + b;

You cannot start a task that has already completed. If you need to run the same task you’ll need to initialise it again.

View the list of posts on the Task Parallel Library here.


A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: