On Task.Factory.StartNew and Task.Run methods (2024)

.NET Programming

By Joydip Kanjilal, Contributor, InfoWorld |

Learn the best practices to create and schedule tasks efficiently in .Net using Task.Run and Task.Factory.StartNew methods

On Task.Factory.StartNew and Task.Run methods (2)

When creating tasks using Task.Factory.StartNew or Task.Run methods, you should keep certain important points in mind when writing asynchronous code. In most cases, it is advisable to avoid using Task.Factory.StartNew method if you are working with asynchronous code. If you are working with parallel code, I would say that StartNew is a good choice.

A task scheduler is a component that is responsible for scheduling tasks; The .Net framework provides you with two task schedulers. There's the default task scheduler that runs on the .Net framework thread pool, and there's the task scheduler that executes on the synchronization context of a specified target. The default task scheduler will suffice most of the time, but you can also build your own custom task scheduler to provide added functionalities. To build your own custom task scheduler you would need to create a class that extends the System.Threading.Tasks.TaskScheduler class.

How do I create Tasks using the Task Parallel Library?

There are several ways in which you can create and start tasks in .Net. You need to make use of the System.Threading.Tasks.Task or System.Threading.Tasks.Task<TResult> class to create tasks (a schedulable unit of work). While the former is used to create a task that doesn't return a value, the latter is used to create tasks that have return values. The Task.Factory property is an instance of the TaskFactory class. This property is used to create and schedule tasks. While the Task.Factory.StartNew method works like a fork operation and is used to create and start new tasks, the Wait method works just like a join operation and waits for the task to be complete.

The following code snippet illustrates how you can use the Task.Factory.StartNew method.

Task.Factory.StartNew(() => TestMethod(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);

You can also create a Task using the Task.Run method as shown in the code snippet below.

public async Task DoSomeWork()

{

await Task.Run(() => TestMethod());

}

void TestMethod()

{

Console.WriteLine("Hello world!");

}

If you would like to return a value from a Task you can take advantage of Task.FromResult method as shown in the code snippet below.

public async Task DoSomeWork()

{

string text = await Task.FromResult<string>(GetMessage());

}

private string GetMessage()

{

return "Hello world!";

}

You can also create tasks using a delegate or an action. The following code snippet shows how you can create tasks using actions and delegates.

Task task1 = new Task (new Action(Display));

task1.Start();

Task task2 = new Task (delegate { Display(); });

task2.Start();

You can also create tasks using lamba and anonymous methods.

Task.Factory.StartNew and Task.Run

Task.Factory.StartNew is a quick way of creating and starting a Task. Note that a call to Task.Factory.StartNew is functionally equivalent to creating a task instance and then calling the Start method on the instance. However, it is not recommended to be used for reasons aplenty. If you would like to execute synchronous code, Task.Factory.StartNew is not a good choice.

Note that if a taskscheduler is available, the StartNew method will execute the task on that taskscheduler. On the contrary, if a scheduler isn't available, it would execute the task on a thread pool thread. It should be noted that Task.Factory.StartNew defaults to TaskScheduler.Current and not TaskScheduler.Default.

Note that a call to Task.Run(action) is equivalent to the following statement: Task.Factory.StartNew(action, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);

On the contrary, a call to Task.Factory.StartNew(action) is equivalent to the following statement:
Task.Factory.StartNew(action, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Current);

If may want to use Task.Factory.StartNew if you have created a custom task scheduler and pass the scheduler instance to it explicitly. I would always recommend using Task.Run as it is much simpler and has safer defaults. In other words, we should avoid using Task.Factory.StartNew unless there is a need to create a task scheduler and then pass it explicitly when calling the StartNew method to create a new task and schedule it. If you were to use the TaskFactory.StartNew method effectively and reliably, you should use a custom task scheduler and then specify the CancellationToken and TaskCreationOptions.

The Task.Run method is recommended to use when you don't need to have much fine-grained control over thread scheduling and its intricacies. You should use Task.Run primarily on CPU bound methods. However, you should use Task.Run while invoking the task and not inside the implementation of the task. In other words, you should use Task.Run not inside any implementation of a method but at the point where the method is called. As an example, the following code snippet is an example of a "bad" piece of code.

public async Task<string> DownloadDataFromWebAsync(Uri uri)

{

return await Task.Run(() =>

{

using (WebClient webClient = new WebClient())

{

return webClient.DownloadString(uri);

}

});

}

Refer to the code snippet given above. The method isn't scalable as it would block the background thread, retrieve a thread from the thread pool and execute synchronously on it. Hence, it would consume more resources in your system.

Next read this:

  • Why companies are leaving the cloud
  • 5 easy ways to run an LLM locally
  • Coding with AI: Tips and best practices from developers
  • Meet Zig: The modern alternative to C
  • What is generative AI? Artificial intelligence that creates
  • The best open source software of 2023

Related:

  • Software Development

Joydip Kanjilal is a Microsoft MVP in ASP.NET, as well as a speaker and author of several books and articles. He has more than 20 years of experience in IT including more than 16 years in Microsoft .NET and related technologies.

Follow

Copyright © 2016 IDG Communications, Inc.

On Task.Factory.StartNew and Task.Run methods (2024)

FAQs

What is the difference between task factory StartNew and task run? ›

Factory. StartNew are both methods in C# that allow for creating and executing tasks asynchronously. Task. Run is a simplified method that makes it easier to create and start a task.

Is it good to use task run? ›

In the previous guide in this series we saw why Task. Run is mainly useful for CPU-bound code. In exploring that topic it became clear that, although you can use Task. Run with other types of operations, it may not be the best use of system resources.

What does task factory do in C#? ›

Creates and starts a task for the specified action delegate, state, cancellation token, creation options and task scheduler.

What is the use of task run in C#? ›

In this example, Task. Run is used to start a complex calculation, simulating a CPU-intensive operation running in a different thread than the one it was called from. By doing this, we free the calling thread (presumably the UI thread) and allow the . NET runtime to handle how and when this operation is executed.

What is the difference between thread start and task run? ›

A Thread is a lower-level implementation while a Task is a higher-level implementation. It takes resources while a Task does not. It also provides more control than the Task class. A Thread should be preferred for any long-running operations, while a Task should be preferred for any other asynchronous operations.

What does task run return? ›

Returns. A task object that represents the work queued to execute in the thread pool.

What is a task runner what are its advantages? ›

The first advantage of using task runners is that they automate the tasks and processes involved in web development. with Task runners, developers will not have to worry about running commands that will involve tedious processes, as these tools are capable of running them for you.

Should I use task from result? ›

Using Task.

FromResult is a sibling to Task. CompletedTask . It is a useful method in async programming to create a completed Task with a specific result. It also allows us to quickly return a completed Task in situations where we don't have asynchronous operations.

What is considered a long running task? ›

Long-running tasks are jobs that will be responsible for tasks that will generally take more time to be executed and will be running in the background. The most common tasks that are considered long-running ones are the following: Moving multiple pages. Deleting user groups.

What is the difference between task and multithreading in C#? ›

While tasks and threads both represent units of work, they differ in several key aspects: Threading Model: Threads are managed by the operating system, while tasks are managed by the runtime environment. Resource Management: Threads require explicit resource management, while tasks are managed by the runtime.

When should I use task in C#? ›

You use Task as the return type if the method has no return statement or has a return statement that doesn't return an operand. You can also specify any other return type, provided that the type includes a GetAwaiter method.

How to run a task asynchronously in C#? ›

The async keyword turns a method into an async method, which allows you to use the await keyword in its body. When the await keyword is applied, it suspends the calling method and yields control back to its caller until the awaited task is complete.

What is Task factory StartNew? ›

Creates and starts a task for the specified action delegate, state, cancellation token, creation options and task scheduler. StartNew(Action, CancellationToken, TaskCreationOptions, TaskScheduler) Creates and starts a task for the specified action delegate, cancellation token, creation options and state.

What is Task method in C#? ›

In C#, a Task is a higher-level abstraction for running code asynchronously. A Task denotes a unit of work that needs to be executed asynchronously, and it may or may not return a value. A Task is usually created with the help of the Task Factory class, which provides several methods for creating and executing Tasks.

How to run multiple tasks in parallel in C#? ›

This is achieved by using the WhenAll method from Task Parallel Library. The Task. WhenAll method creates a Task that will be complete when all the supplied tasks have been completed. Once all three Tasks are complete, we await the individual Task instances to derive the result from them.

What is run with highest privileges Windows task? ›

The "Run with highest privileges" option should be used when a task requires administrator rights to execute properly. Enabling this option ensures the task runs with elevated privileges, granting it access to perform administrative actions.

What is the difference between a thread and a task? ›

Tasks are more lightweight than Threads. Tasks use fewer system resources, such as memory and CPU time, compared to Threads. Tasks are easier to manage than Threads. Tasks provide a higher-level abstraction for asynchronous programming, which makes it easier to write and maintain code.

When to use task WhenAll in C#? ›

The Task. WhenAll method in C# allows you to create a task that is completed when a group of other tasks have finished executing. This can be useful when you want to wait for multiple tasks to complete before moving on to other parts of your code.

References

Top Articles
Latest Posts
Article information

Author: Gregorio Kreiger

Last Updated:

Views: 6033

Rating: 4.7 / 5 (77 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Gregorio Kreiger

Birthday: 1994-12-18

Address: 89212 Tracey Ramp, Sunside, MT 08453-0951

Phone: +9014805370218

Job: Customer Designer

Hobby: Mountain biking, Orienteering, Hiking, Sewing, Backpacking, Mushroom hunting, Backpacking

Introduction: My name is Gregorio Kreiger, I am a tender, brainy, enthusiastic, combative, agreeable, gentle, gentle person who loves writing and wants to share my knowledge and understanding with you.