CodeBlanks Logo Icon CodeBlanks

Starting tasks

C# course · Advanced · Lesson 7/83

Learn to start tasks with Task.Run and Task.Factory.StartNew.

Ways to start a Task

In C# you start a Task in a few ways: call an async method and await it (cleanest), offload CPU work with Task.Run, or build a ready-result Task with Task.FromResult.

Older code used new Task(...) followed by .Start(); this is no longer recommended. The Thread class is lower level and is not used in place of async/await. For new code, embrace async method + await.

Task.Run vs new Task

Task.Run immediately sends work to the pool and returns a Task. new Task(...) creates the Task but does not start it; you must also call .Start(). This extra step is error-prone.

So new code prefers Task.Run. For CPU work use the await Task.Run(() => Work()) pattern. For I/O call an async method directly; do not waste a pool thread.

Exercise Start work with Task.Run

Define static string BuildMessage() (return "Ready";). Make Main a static async Task Main. Produce the message in the pool with string msg = await Task.Run(() => BuildMessage()); and print with Console.WriteLine(msg);.

Show example solution
In BuildMessage body write return "Ready";. Make Main static async Task Main() and write string msg = await Task.Run(() => BuildMessage()); Console.WriteLine(msg);
Example solution:
using System;
using System.Threading.Tasks;

class Program
{
    static string BuildMessage()
    {
        return "Ready";
    }

    static async Task Main()
    {
        string msg = await Task.Run(() => BuildMessage());
        Console.WriteLine(msg);
    }
}

Test yourself

  1. What is the recommended way to start a Task?

    • new Task(() => {})
    • async method call + await
    • Thread.Start
    • ThreadPool.QueueUserWorkItem
    Show answer

    async method call + await — Correct. An async method call + await is the cleanest way to start.

  2. Complete the Task.Run call

    Task t = Task.____(() => Work());
    Show answer
    Task t = Task.Run(() => Work());
  3. What does Task.Run return?

    • void
    • Thread
    • Task
    • IEnumerable
    Show answer

    Task — Correct. Task.Run returns a Task; you await it.

All lessons in Advanced