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));
task.Start();

…where PrintMessage is a method:

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

Using a delegate

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

Lambda and named method

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

Lambda and anonymous method

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

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.

Advertisements

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

35 Responses to 7 ways to start a Task in .NET C#

  1. Stefan Ossendorf says:

    Don’t forget Task.Run(() => PrintMessage()) or Task.FromResult(42).

    Nice Reference:
    http://msdn.microsoft.com/en-us/magazine/jj991977.aspx

  2. Cellfish says:

    As Stefan points out Task.Run and Task.FromResult are the only two alternatives you need to care about except Task.Factory.StartNew. Especially look at figure 9 in Stefan’s link. The Task constructor and Task.Start and patterns that you are recommended to avoid.
    All your variants of delegates etc still apply, just don’t push for the task.Start pattern.

  3. Steven says:

    Good to know how to use the Task in 7 ways. Thanks man.

  4. Pingback: 7 ways to start a Task in .NET C# | kiizoo

  5. rohan says:

    can you please do one more blog on how async and await are used in asp.net mvc , i am trying to understand but its confusing 😦 . Thanks a lot , i liked this blog a lot.

  6. sameer sapra says:

    Can you tell me one thing…When we call printmessage() in task.run, will this be called asynchronously or synchronously?

    • Andras Nemes says:

      Hello Sameer,

      Asynchronously if the caller calls it with await:

      public async Task DoRun()
      {
      	await DoRunAsync();
      }
      
      public async Task DoRunAsync()
      {
      	Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
      	await Task.Run(() => { PrintMessage(); });
      	Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
      }
      

      The managed thread IDs will most often differ before and after Task.Run.

      //Andras

  7. Pingback: Les nouveaux chemins vers l’asynchronisme – III | Nouvelles Chroniques d'Amethyste

  8. eastjie says:

    Reblogged this on 天天学习,好好向上 and commented:
    About Task.Start

  9. smdrager says:

    You have a minor misnomer in your article where you call an expression lambda passing a named method. You could actually make this article “8 ways to start a task” if you add the additional one.

    Named method

    Task task = new Task( PrintMessage );
    task.Start();

    Expression lambda

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

    Statement lambda

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

  10. Zinov says:

    Task.Factory.StartNew()

  11. Pingback: Async WCF | Vincent

  12. Hey Andras.

    Easy question: what tool/app do you use to compose these posts? Are you composing them in WP or using another tool, and pasting them into your WP instance?

    Just trying to get an idea for a good workflow for my own blog.

    Thanks.

    • Andras Nemes says:

      Hi Brent, I use WordPress, nothing else. It has an editor which suits all my needs – which are not too complex for that matter. I only need to show text, code and images. If I want to insert a diagram then I first build it in e.g. MS Visio and then insert it as an image into the post. //Andras

  13. Pingback: C#: Snippets | RaSor's Tech Blog

  14. Pingback: Confluence: [PGS] .NET

  15. Pingback: Threading with Parameters | connectvishal

  16. Josh says:

    Any resources on how to use these things on windows forms such as updating a text box or something via the ways described here?

  17. greens says:

    very nice short explanation !

  18. Pingback: Asynkron programmering i .NET – Hauns™

  19. Yuriy says:

    Thanks for your notes. I found it useful.

  20. Hidalgo says:

    Hello Andras,
    Could you please help me understand something. I need to execute a process (run external program) asynchronously (so that the application does not wait for the process to finish and continue). I tried the following:
    Task.Factory.StartNew(() => Process.Start( “PrintOrder.exe”, nOrderNumber.ToString()));
    But it does not make a different; the application still waits on the above line for almost a minute.
    In your answer on Decc 21, 2014 you said “Asynchronously if the caller calls it with await:”
    How do I apply the “await” to my syntax above?
    Thank you in advance.

    • Andras Nemes says:

      Hello, the StartNew() method starts a new task on a different thread and code execution should not wait for it to finish. Do you have a call to Task.Wait somewhere after this? I cannot provide a full response regarding async-await in a comment field. If you are new to asynchronous methods then start here:
      https://dotnetcodr.com/2012/12/31/await-and-async-in-net-4-5-with-c/

      You’ll find a number of examples there to get you started.

      //Andras

      • Hidalgo says:

        Andras, Thank you very much for replying. I don’t have Task.wait call. And you are right that I am new to the asynchronous methods and I will go to your article and study it.
        Again, thank you!

  21. Kundan Kumar Rai says:

    Hi Andras Nemes,

    I am using –

    Task task = new Task(delegate { GetRecordsForEmailReplies(headingList, partialEntity); });
    task.Start();

    to run some heavy methods, but the problem is it’s consuming lots of space of CPU on server and some time server gets stuck.
    Is there any solution to manage this problem, so please le me know?

    Thanks in advance.

    Thanks,
    Kundan

    • Andras Nemes says:

      Hi Kundan, if a process consumes a lot of CPU then I don’t think threading by itself will solve the problem. It sounds more like a code optimisation and /or hardware capacity issue. How many CPU cores does the server have where the code is executed? Can you check the consumption of each CPU during the execution? Is it even or is it just one core taking the entire load? //Andras

  22. Pingback: Parallel Operations [TPL] – Nitesh Kumar

  23. Pingback: Task Operations – Nitesh Kumar

  24. Pingback: How to perform C# Asynchronous operations • Dot Net For All

  25. JTS says:

    Hi Andras Nemes,

    I’ve created as async function that do some heavy computation and the function accept a list that contains millions of data.

    My target is after the execution of the task, the list parameter that is being pass to the function must be set to null/empty.

    How can i achieve that? any idea?

    here is my code:

    public async void AsyncCompute(Dictionary<string, List> ListClazz)
    {
    string ky = string.Empty;
    foreach (KeyValuePair<string,List> element in ListClazz)
    {
    ky = element.Key;
    await Task.Run(() => HeavyComputation(element.Value,ky));
    }

    ListClazz.Clear();
    }

    Note: I’ve got an error with this because the list got null even all tasks were not yet done.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

iReadable { }

.NET Tips & Tricks

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

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: