Baike.dev
All toolsAI codingTrendingOpen sourceNewsSubmit
Log in
Back to tool/Back to issues
#64·AspNetCoreDiagnosticScenarios

Make TaskCreationOptions.LongRunning advice more explicit

Author: bartelinkCreated Jul 7, 2020Updated May 21, 2021

There's a note regarding avoidance of TaskCreationOptions.LongRunning:

NOTE:Task.Factory.StartNew has an option TaskCreationOptions.LongRunning that under the covers creates a new thread and returns a Task that represents the execution. Using this properly requires several non-obvious parameters to be passed in to get the right behavior on all platforms.

The code sample then proceeds to use:

var thread = new Thread(ProcessQueue) 
    {
        // This is important as it allows the process to exit while this thread is running
        IsBackground = true
    };
    thread.Start();

The bit I'm missing is how we go from "API is awkward" to "look, you're better off with Thread.Start"; is it for reasons of cumbersome syntax or is it because it's outright better and/or TaskCreationOptions.LongRunning should all-but be deprecated that we go to the lengths of actually creating a thread explicitly? I propose to use the answer to either a) make a PR to switch the example to use Task.Factory.StartNew, or b) clarify the note to explicitly indicate that Task.Factory.StartNew should be avoided, and (Thread {IsBackground = true}).Start() is the recommended alternative

For instance in Serilog.Sinks.Async, we create the thread using TaskCreationOptions.LongRunning

Source: davidfowl/AspNetCoreDiagnosticScenarios

View original on GitHubView discussion on GitHub