Asdevelopers, running critical tasks in the background can open up a world of problem-solving possibilities. Background services are ideal for many scenarios, especially if your users are willing to wait for results. Some use-case scenarios for background services include updating globally-used caches, processing queued work, and general health monitoring.
With the host, you can predictably manage the starting and stopping of your application, allowing your application to behave more gracefully when those events occur. The host also tracks the lifetime of registered services, whether singleton, scoped, or transient, via an IServiceProvider instance. Finally, the host will also be responsible for starting any registered background services.
Your host application is not limited to a single background service. You can register any number of services, but be aware that the more registered services there are in a host, the greater the likelihood that a single background service could cause issues for other services. You can certainly write your code to be more resilient, but the standard practice for catastrophic background service failures is to restart the process.
Job libraries are the most common use for background services in the .NET space. These libraries allow you to create recurring jobs, queue jobs to be processed asynchronously, or perform fire-and-forget operations.
The call to AddHangfireServer registers a BackgroundJobServerHostedService, which will handle all jobs in the designated database. To run a job in the background service, call the method Enqueue on an IBackgroundJobClient.
Messaging and Actor frameworks sit in another category of libraries that can sometimes utilize background services, allowing you to send distributed messages. These distributed frameworks are trendy in the .NET space as they will enable you to scale your applications up, out, and in any combination. Current popular choices include Wolverine, MassTransit, Brighter, Akka.NET, and Proto.Actor.
Wolverine uses a background service called WolverineRuntime, which pairs messages to their destination handlers. With the current code, Wolverine handles all messages in memory, but you can store messages in a variety of backing stores, including SQL Server, PostgreSQL, and RabbitMQ.
By submitting this form, I agree that JetBrains s.r.o. ("JetBrains") may use my name, email address, and location data to send me newsletters, including commercial communications, and to process my personal data for this purpose. I agree that JetBrains may process said data using third-party services for this purpose in accordance with the JetBrains Privacy Policy. I understand that I can revoke this consent at any time in my profile. In addition, an unsubscribe link is included in each email.
Game development has entered a new era with the rise of AI-powered tools. But where is AI truly helpful, and where should we tread carefully? Join JetBrains Developer Advocates as they explore the role of AI in game development and showcase the capabilities of JetBrains AI Assistant.
This information relates to a pre-release product that may be substantially modified before it's commercially released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
In
ASP.NET Core, background tasks can be implemented as hosted services. A hosted service is a class with background task logic that implements the IHostedService interface. This article provides three hosted service examples:
Use the Worker Service (worker) template with the dotnet new command from a command shell. In the following example, a Worker Service app is created named ContosoWorker. A folder for the ContosoWorker app is created automatically when the command is executed.
An app based on the Worker Service template uses the Microsoft.NET.Sdk.Worker SDK and has an explicit package reference to the Microsoft.Extensions.Hosting package. For example, see the sample app's project file (BackgroundTasksSample.csproj).
For web apps that use the Microsoft.NET.Sdk.Web SDK, the Microsoft.Extensions.Hosting package is referenced implicitly from the shared framework. An explicit package reference in the app's project file isn't required.
The hosted service is activated once at app startup and gracefully shut down at app shutdown. If an error is thrown during background task execution, Dispose should be called even if StopAsync isn't called.
ExecuteAsync(CancellationToken) is called to run the background service. The implementation returns a Task that represents the entire lifetime of the background service. No further services are started until ExecuteAsync becomes asynchronous, such as by calling await. Avoid performing long, blocking initialization work in ExecuteAsync. The host blocks in StopAsync(CancellationToken) waiting for ExecuteAsync to complete.
The cancellation token is triggered when IHostedService.StopAsync is called. Your implementation of ExecuteAsync should finish promptly when the cancellation token is fired in order to gracefully shut down the service. Otherwise, the service ungracefully shuts down at the shutdown timeout. For more information, see the IHostedService interface section.
A timed background task makes use of the System.Threading.Timer class. The timer triggers the task's DoWork method. The timer is disabled on StopAsync and disposed when the service container is disposed on Dispose:
The Timer doesn't wait for previous executions of DoWork to finish, so the approach shown might not be suitable for every scenario. Interlocked.Increment is used to increment the execution counter as an atomic operation, which ensures that multiple threads don't update executionCount concurrently.
The default behavior can be changed so that the hosted service's StartAsync runs after the app's pipeline has been configured and ApplicationStarted is called. To change the default behavior, add the hosted service (VideosWatcher in the following example) after calling ConfigureWebHostDefaults:
3a8082e126