Tuesday, October 26, 2021

Can we read console inputs in .Net Core BackgroundService?

Alert: This is a basic question-answer post for my tailored googling purpose. you may easily skip this post.

Background

.Net Core API model simplified many things such as dependency injection, logging, etc...One major thing is the background service to perform background operations. There are many use cases for BackgroundService. More of how to use BackgroundService and its interface IHostedService and how to host can be found in the official documentation.

Question

When we use BackgoundService, one simple question may arise in our minds. Can we get user input from the console by the code running inside the BackgroundService?

Answer

The answer is yes we can get the inputs from the console. There is a sample available in my GitHub repo that acts as a template for .Net console apps.

Why this post?

This post is mainly for my tailored googling purpose. I got this question 2-3 times. Next time I can search it easily by prefixing joymon😀

Interesting links regarding BackgroundService hosting

https://docs.microsoft.com/en-us/dotnet/architecture/microservices/multi-container-microservice-net-applications/background-tasks-with-ihostedservice

https://medium.com/@daniel.sagita/backgroundservice-for-a-long-running-work-3debe8f8d25b

No comments: