Last active
September 12, 2023 00:51
-
-
Save cheenamalhotra/b47770f5fbc7330aa79968a8999c8884 to your computer and use it in GitHub Desktop.
Task.Factory.Run v/s Task.Run
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Runtime.CompilerServices; | |
namespace Example | |
{ | |
public class TestTaskRun | |
{ | |
static async Task Main() | |
{ | |
// Task.Run: Waits for print an delay task to complete first. | |
await Run("Task.Run", async () => await Task.Run(async () => await PrintAndDelayAsync("Task.Run", 1))); | |
// Task.Factory.StartNew: Starts a detached task that completes on its own. | |
await Run("Task.Factory.StartNew", async () => await Task.Factory.StartNew(async () => await PrintAndDelayAsync("Task.Factory.StartNew", 1))); | |
// Allow tasks to complete. | |
await Task.Delay(2000); | |
} | |
static async Task Run(string funcName, Func<Task> func) | |
{ | |
Console.WriteLine($"\n{funcName} started."); | |
await func(); | |
Console.WriteLine($"{funcName} completed."); | |
} | |
static async Task PrintAndDelayAsync(string name, int seconds = 0, [CallerMemberName] string caller = "") | |
{ | |
Console.WriteLine($"{caller}: PrintAndDelayAsync ({name}): Entered."); | |
await Task.Delay(seconds * 1000); | |
Console.WriteLine($"{caller}: PrintAndDelayAsync ({name}): {seconds} seconds delay completed."); | |
} | |
} | |
} | |
/** Output: | |
> dotnet run | |
Task.Run started. | |
Main: PrintAndDelayAsync (Task.Run): Entered. | |
Main: PrintAndDelayAsync (Task.Run): 1 seconds delay completed. | |
Task.Run completed. | |
Task.Factory.StartNew started. | |
Main: PrintAndDelayAsync (Task.Factory.StartNew): Entered. | |
Task.Factory.StartNew completed. | |
Main: PrintAndDelayAsync (Task.Factory.StartNew): 1 seconds delay completed. | |
*/ | |
/** | |
As captured in Output, Task.Run attaches the async task to main thread, thereby blocking the main thread, until it completes. | |
Task.Factory.StartNew on the other hand, creates a detached task that executes in backend, not blocking Main thread from continuing executing. | |
Therefore, use Task.Factory.StartNew where non-blocking async tasks are desired. | |
And for creating async tasks, where blocking/non-blocking is not a concern, Task.Run can be used to make sync code run asynchronously. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment