It’s natural to exploit the relative new feature of ASPNET 2.0 called IHostedService to schedule background async tasks.

In order to start, the implementation of the interface needs to be added to services:

Since this ASPNET will manage background thread life cycle calling StartAsync and StopAsync methods of the service. Those methods are to accept and handle CancellationToken parameter in order to gracefully complete the tasks and can be implemented in pretty simple code. Since next 2.1 version of ASPNET there will be an abstract class to implement this interface and make the things even simpler, so it’s worth to borrow that class

Now we have to extend this abstract class and implement exactly one method:

Build, run, see log messages every 5 seconds, enjoy. Very simple.

Categories: Development

Leave a Reply

Your email address will not be published. Required fields are marked *