诺禾、Dotnet Core的后台任务

本文介绍了如何在Dotnet Core中创建后台任务,包括WebAPI下实现IHostedService接口的托管服务和Console应用的简单实现。通过示例代码展示了定时任务的创建,并探讨了Console应用作为Service的配置方法。
摘要由CSDN通过智能技术生成

一、前言
后台任务在一些特殊的应用场所,有相当的需求。

比如,我们需求完成一个定时任务、或周期性的任务、或非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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值