Home >Backend Development >C++ >Task.Run() vs. Task.Factory.StartNew(): When Should You Use Which?

Task.Run() vs. Task.Factory.StartNew(): When Should You Use Which?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-12 08:58:41667browse

Task.Run() vs. Task.Factory.StartNew(): When Should You Use Which?

.NET asynchronous programming: Comparison of Task.Run() and Task.Factory.StartNew()

In .NET asynchronous programming, it is often necessary to create and start new tasks. For this purpose, the .NET framework provides two commonly used methods: Task.Run() and Task.Factory.StartNew(). While both achieve the same basic goal, their functionality and use cases differ.

Task.Factory.StartNew()

Task.Factory.StartNew()More feature-rich, providing multiple options to customize the behavior of new tasks. Some of the key parameters it accepts include:

  • Action/Func: Delegate to be executed in a new task.
  • CancellationToken: A cancellation token that can be used to abort the task.
  • TaskCreationOptions: A set of options that control the behavior of a task, such as its creation options and scheduler.
  • TaskScheduler: The scheduler that will execute the task.

This flexibility allows you to tailor tasks to your specific needs, such as creating long-running tasks or executing tasks on specific threads.

Task.Run()

Task.Run() is a simplified version of Task.Factory.StartNew() introduced in .NET 4.5. It provides a default configuration for new tasks, using the following settings:

  • CancellationToken.None: Does not use cancellation token.
  • TaskCreationOptions.DenyChildAttach: Subtasks created by new tasks cannot be attached to the original task.
  • TaskScheduler.Default: The task will run on the default task scheduler, usually using a thread pool.

is a convenient choice when you don't need any special customization and just use the default settings to quickly start a new task. Task.Run()

When to use Task.Run() vs. Task.Factory.StartNew()

In general, use

when you need to customize the behavior of a new task. This includes the following scenarios: Task.Factory.StartNew()

    Create long-running tasks
  • Specify a specific cancellation policy
  • Execute tasks on a specific thread or thread pool
Use

when you don’t need any customization and just create a new task with default settings. Task.Run() is a shortcut that simplifies task creation without additional configuration. Task.Run()

The above is the detailed content of Task.Run() vs. Task.Factory.StartNew(): When Should You Use Which?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn