im trying to figuring out how C#
manages threads.
I just started up new Web Api
project. I packed it to new Thread
:
public class Program
{
public static void Main(string[] args)
{
var thread = new Thread(() => CreateHostBuilder(args).Build().Run());
thread.Start();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
// DEFAULT STARTUP HERE
.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
}
And i added my custom controller to it:
[ApiController]
[Route("[controller]")]
public class ValueController : ControllerBase
{
[HttpGet("fast")]
public async Task<ActionResult<int[]>> Fast()
{
var task = new Task<int[]>(() =>
{
return new[] {1, 2, 3};
});
task.Start();
return Ok(await task);
}
[HttpGet("infinite")]
public async Task<ActionResult<int[]>> Infinite()
{
var task = new Task<int>(() =>
{
while (true)
{
}
return 0;
});
task.Start();
return Ok(await task);
}
}
First, i run https://localhost:5001/value/infinite
endpoint to have one task that never ends in the background.
Then i started to spam my app with https://localhost:5001/value/infinite
endpoint.
As you can see in debugger:
First run of endpoint:
Second:
The whole ASP .NET
app work on the same thread that with number @13272
.
My question is, how .NET
manage Tasks
in one thread when it is possible to run multiple tasks when there are infinite tasks running in the background?