A simple hosted service running in a console application.
1 | class Program |
MyBackgroundService
1 | using Microsoft.Extensions.Hosting; |
MyHostedService
1 | using Microsoft.Extensions.Hosting; |
FooService
This will create a worker that does some background work. The complete code for these snippets is at https://github.com/carlpaton/ThreadingDemo/tree/main/src/HostedService.Ca
- Create the empty console application
- Add
Microsoft.Extensions.Hosting
- Create
FooService
which inherits and implementsBackgroundService
1 | public class FooService : BackgroundService |
- Update
Program.cs
to add your worker/service to as a hosted service with.AddHostedService
. My service below isFooService
1 | static void Main(string[] args) |
- Update
FooService
to do something, here we just write to the console every 2 seconds. Microsoft suggest the following things you could use this for
- A background task polling a database looking for changes.
- A scheduled task updating some cache periodically.
- An implementation of QueueBackgroundWorkItem that allows a task to be executed on a background thread.
- Processing messages from a message queue in the background of a web app while sharing common services such as ILogger.
- A background task started with Task.Run().
1 | public class FooService : BackgroundService |
“By default, the cancellation token is set with a 5 seconds timeout, although you can change that value when building your WebHost using the UseShutdownTimeout extension of the IWebHostBuilder. This means that our service is expected to cancel within 5 seconds otherwise it will be more abruptly killed.”
References
- https://medium.com/@nickfane/queue-processing-with-net-core-worker-services-eaccff28ba69
- https://docs.microsoft.com/en-us/dotnet/architecture/microservices/multi-container-microservice-net-applications/background-tasks-with-ihostedservice
- https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host