Skip to content

Instantly share code, notes, and snippets.

@up1
Last active April 27, 2021 16:04
Show Gist options
  • Save up1/647689dbc084b1d0e328554521008a10 to your computer and use it in GitHub Desktop.
Save up1/647689dbc084b1d0e328554521008a10 to your computer and use it in GitHub Desktop.
.Net Core :: Slow first response
$curl -o /dev/null -s -w %{time_total}\\n https://localhost:5001
0.470427
$curl -o /dev/null -s -w %{time_total}\\n https://localhost:5001
0.034931
$curl -o /dev/null -s -w %{time_total}\\n https://localhost:5001
0.037043
# Start server
$dotnet dist/test.dll
info: Microsoft.Hosting.Lifetime[0]
Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
Now listening on: https://localhost:5001
info: Application.WarmupServices[0]
Starting IHostedService...
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
# Result
$curl -o /dev/null -s -w %{time_total}\\n https://localhost:5001
0.040194
$curl -o /dev/null -s -w %{time_total}\\n https://localhost:5001
0.035138
$curl -o /dev/null -s -w %{time_total}\\n https://localhost:5001
0.028956
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureServices(
services => services.AddHostedService<WarmupServices>());
}
public class WarmupServices : IHostedService, IDisposable
{
private readonly ILogger _logger;
private readonly HttpClient httpClient;
public WarmupServices(ILogger<WarmupServices> logger)
{
_logger = logger;
httpClient = new HttpClient();
}
public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Starting IHostedService...");
httpClient.GetAsync("<Endpoint URL>");
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("StoppingIHostedService...");
return Task.CompletedTask;
}
public void Dispose()
{
httpClient?.Dispose();
}
}
@alirafique99
Copy link

so this will start http server and send first request as well? to make it quick for actual first request?

@up1
Copy link
Author

up1 commented Apr 27, 2021

so this will start http server and send first request as well? to make it quick for actual first request?
yes, my result in file 2.txt

@alirafique99
Copy link

Beautiful

@alirafique99
Copy link

simple but effective

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment