一、前言
后台任务在一些特殊的应用场所,有相当的需求。
比如,我们需求完成一个定时任务、或周期性的任务、或非API输出的业务响应、或不允许并发的业务处置,像提现、支付回调等,都需求用到后台任务。
通常,我们在完成后台任务时,有两种选择:WebAPI和Console。
下面,我们会用实践的代码,来理清这两种工程形式下,后台任务的开发方式。
为了避免不提供原网址的转载,特在这里加上原文链接:https://www.cnblogs.com/tiger-wang/p/13081020.html
二、开发环境&根底工程
这个Demo的开发环境是:Mac + VS Code + Dotnet Core 3.1.2。
$ dotnet --info
.NET Core SDK (reflecting any global.json):
Version: 3.1.201
Commit: b1768b4ae7
Runtime Environment:
OS Name: Mac OS X
OS Version: 10.15
OS Platform: Darwin
RID: osx.10.15-x64
Base Path: /usr/local/share/dotnet/sdk/3.1.201/
Host (useful for support):
Version: 3.1.3
Commit: 4a9f85e9f8
.NET Core SDKs installed:
3.1.201 [/usr/local/share/dotnet/sdk]
.NET Core runtimes installed:
Microsoft.AspNetCore.App 3.1.3 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.App]
Microsoft.NETCore.App 3.1.3 [/usr/local/share/dotnet/shared/Microsoft.NETCore.App]
首先,在这个环境下树立工程:
创立Solution
% dotnet new sln -o demo
The template “Solution File” was created successfully.
这次,我们用Webapi创立工程
% cd demo
% dotnet new webapi -o webapidemo
The template “ASP.NET Core Web API” was created successfully.
Processing post-creation actions…
Running ‘dotnet restore’ on webapidemo/webapidemo.csproj…
Restore completed in 179.13 ms for demo/demo.csproj.
Restore succeeded.
% dotnet new console -o consoledemo
The template “Console Application” was created successfully.
Processing post-creation actions…
Running ‘dotnet restore’ on consoledemo/consoledemo.csproj…
Determining projects to restore…
Restored consoledemo/consoledemo.csproj (in 143 ms).
Restore succeeded.
把工程加到Solution中
% dotnet sln add webapidemo/webapidemo.csproj
% dotnet sln add consoledemo/consoledemo.csproj
根底工程搭建完成。
三、在WebAPI下完成一个后台任务
WebAPI下后台任务需求作为托管效劳来完成,而托管效劳,需求完成IHostedService接口。
首先,我们需求引入一个库:
% cd webapidemo
% dotnet add package Microsoft.Extensions.Hosting
引入后,我们就有了IHostedService。