Thursday, 8 November 2018

.NET Core Web App as Windows Service : Handling slow startup

.NET core is fast becoming the first choice of development framework as it brings the benefit of cross-platform compatibility. Of course, it is fast too.

If you make a .NET core web application, you would notice that the IWebHost presents us with 2 ways to host the web application 

1. Run
2. RunAsService

RunAsService is quite useful if you want to host your .NET core web application as a windows service instead of a standalone executable. RunAsService does not give us with much flexibility though. 

Enhancement

If you want to handle what happens before ASP.NET core starts or after it has started, you are better suited to inherit from "WebHostService" class and use that to host the asp.net web application.

It is described here.

With this, you will be able to hook your custom code in following places.

1. OnStarting
2. OnStarted
3. OnStopping
4. OnStopped

Enhancement 2

If your start up code is a bit slow, then you have further challenges. In classic windows service projects, you get an option to request additional start up time though code. However, you can not do that in .NET core's web host as those hook points are not available.

So what do you do?

Couple of options:

1. Move your slow start up logic to background thread using Tasks.
2. Use parallel tasks.
3. Use timer to call back into the logic to perform start up work after some time :).

No comments:

Post a Comment