Skip to main content.

Site Map

Site Map

Background Processes

A microservice should provide the ability to run background processes and tasks.

We provide background processing solutions for ordered, period-defined or anytime invocation. This provides a microservice with multiple ways to schedule and perform background task processing.

Defining a Background Task

We define a background task by using two generic interfaces, ITaskDetail and ITaskWork. The ITaskDetail interface defines the model for parameters passed in relating to the task's execution. The ITaskWork interface defines the logic that runs based on the passed in parameters.

The following example defines a simple background task that logs an information message.

public class ExampleLoggingTask
{
    public class Detail : ITaskDetail<Detail, Worker>
    {
        public Detail(string logMessage)
        {
            LogMessage = logMessage;
        }

        public string LogMessage { get; set; }
    }

    public class Worker : ITaskWork<Detail, Worker>
    {
        private readonly ILogger _logger;

        public Worker(ILogger logger)
        {
            _logger = logger;
        }

        public Task DoWork(Detail detail, CancellationToken cancellationToken)
        {
            _logger.LogInformation(detail.LogMessage);
            return Task.CompletedTask;
        }
    }
}

In order for dependency injection to work properly, you must register the Worker class. This is done with the AddBrick extension method by adding the following line:


    services.AddScoped<ExampleLoggingTask.Worker>();

Queue-based Processing

The Service Brick Core library contains an implementation of queue-based, task processing service called TaskQueueHostService. This service provides ordered execution of tasks using a ConcurrentQueue.

To execute the ExampleLoggingTask defined above on the queue, you must first inject a reference to the ITaskQueue interface. After obtaining it, you would queue the task to be processed using the following command:


public ExampleDependencyInjection(ITaskQueue taskQueue)
{
    var detail = new ExampleLoggingTask.Detail("Hello World");
    taskQueue.Queue<ExampleLoggingTask.Detail, ExampleLoggingTask.Worker>(detail);
}

Timer-based Processing

The Service Brick Core library contains an implementation of timer-based, task processing service called TaskTimerHostedService. This service provides execution of tasks using a defined period.

To execute the ExampleLoggingTask defined above using a timer, you must first define a timer for it. You define a timer the following way:


public class ExampleTimer : TimerHostedService<ExampleLoggingTask.Detail, ExampleLoggingTask.Worker>
{
    public ExampleTimer(
        IServiceProvider serviceProvider,
        ILoggerFactory logger) : base(serviceProvider, logger)
    {
    }

    public override TimeSpan TimerTickInterval
    {
        get { return TimeSpan.FromSeconds(30); }
    }

    public override TimeSpan TimerDueTime
    {
        get { return TimeSpan.FromSeconds(30); }
    }

    public override ITaskDetail<ExampleLoggingTask.Detail, ExampleLoggingTask.Worker> TaskDetail
    {
        get { return new ExampleLoggingTask.Detail("Hello World"); }
    }

    public override bool TimerTickShouldProcessRun()
    {
        return ApplicationBuilderExtensions.BrickStarted && !IsCurrentlyRunning;
    }
}

You must register the ExampleTimer class with dependency injection as a hosted service. This is done with the AddBrick extension method by adding the following line:


    services.AddHostedService<ExampleTimer>();

The timer defined above also has the ability to execute the task using the ITaskQueue service if needed by returning true from the DoWorkOnQueue property.

3rd Party and Standard .NET Core Tasks

Along with our managed background task processing, you can also use built-in .NET Core Tasks for processing as well. This is done with the Task.Run() and TaskFactory classes. Our recommendation is to use Azure functions or AWS labdas in a seperate process outside of ASP.NET. You can also use 3rd party, non-cloud based solutions such as Hangfire for scheduling and resiliency. This provides a more reliable approach because a web server can be shutdown at any time.