Thisinformation 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:
StartAsync should be limited to short running tasks because hosted services are run sequentially, and no further services are started until StartAsync runs to completion. Long running tasks should be placed in ExecuteAsync. For more information, see the source to BackgroundService.
.NET Framework developers are probably familiar with Windows Service apps. Before .NET Core and .NET 5+, developers who relied on .NET Framework could create Windows Services to perform background tasks or execute long-running processes. This functionality is still available and you can create Worker Services that run as a Windows Service.
Installing the .NET SDK also installs the Microsoft.NET.Sdk.Worker and the worker template. In other words, after installing the .NET SDK, you could create a new worker by using the dotnet new worker command. If you're using Visual Studio, the template is hidden until the optional
ASP.NET and web development workload is installed.
To create a new Worker Service project with Visual Studio, you'd select File > New > Project.... From the Create a new project dialog search for "Worker Service", and select Worker Service template. If you'd rather use the .NET CLI, open your favorite terminal in a working directory. Run the dotnet new command, and replace the with your desired project name.
To install this from Visual Studio, use the Manage NuGet Packages... dialog. Search for "Microsoft.Extensions.Hosting.WindowsServices", and install it. If you'd rather use the .NET CLI, run the dotnet add package command:
The preceding joke service source code exposes a single piece of functionality, the GetJoke method. This is a string returning method that represents a random programming joke. The class-scoped _jokes field is used to store the list of jokes. A random joke is selected from the list and returned.
In the preceding code, the JokeService is injected along with an ILogger. Both are made available to the class as fields. In the ExecuteAsync method, the joke service requests a joke and writes it to the logger. In this case, the logger is implemented by the Windows Event Log - Microsoft.Extensions.Logging.EventLog.EventLogLoggerProvider. Logs are written to, and available for viewing in the Event Viewer.
3a8082e126