"Knowledge has to be improved, challenged, and increased constantly, or it vanishes."

Archives

Archives / 2021 / October
  • Running background tasks in ASP.Net applications

    While developing applications, you may come across various occasions where you create background services to achieve automation in your applications. Such services include sending notification, update a user’s subscription expiration or may be changing the state of a workflow activity and so on.

    Developers use Windows Service, Cron jobs or Executables that works in a separate thread than your web applications that works based on a schedule. In .Net, for creating a background task, developers mainly use the Console Application or Windows Service template. While this will do the job, it adds some complexity. Few of the issues developers face with background services are below

    • You may use configuration files in the web application such as connection string, logs file path etc, however for the console application, you need to redefine them under its application settings, something your operation team will not prefer, of course this adds operations complexity.
    • Migrating the application may lead to troubles as I have seen several times, the migration happens without migrating the background service and then developers troubleshoot and identifies they forgot some of the services.
    • Modifying the code in the application and database structure may impact the background service.
    • And many more


    Though it had limitations, developers used it a lot especially when they need to implement background services. Now with the ASP.Net framework has built in capability to run background tasks from the web application itself. Cool, for many of you, it must be music to your ears, now from the same project you can manage your pages, application logic and background services.

    Background Service in Asp.Net application

    In ASP.Net background tasks can be implemented as hosted services. In this article, I am going to demonstrate how you can develop a background service in ASP.Net

    For the purpose of this demo, I used the following environment.

      • ASP.Net 6
      • Visual Studio 2022 Preview
      • ASP.Net Web application


    Also, I have a class in my application called Task that has a due date and Is Completed flag. I have a page that create a task by setting a due date. Now I am going to create a background service in ASP.Net application itself that set IsCompleted to true for tasks when it reaches the due date.

    See the Task class below.

    public class Task { public int Id { get; set; } public string Title { get; set; } public DateTime DueDate { get; set; } public bool IsCompleted { get; set; } public DateTime ActionDate { get; set; } }