asp.net-core - 如何使用 SignalR 获得延迟响应(控制器调用后台服务)?
问题描述
我阅读了有关 SignalR 的文档和教程。但我不明白如何在我的情况下得到回应。
.Net5。
Reactjs 向 Controller 发送请求。
控制器动作:
[HttpGet("compared")]
public async Task<ActionResult> GetComparedText([FromQuery] PrevDraftVersionDto dto) =>
Ok(await _mediator.Send(new GetComparedTextQuery(dto.InitialDraftId, dto.DraftId, dto.CurrVer, dto.PrevVer)));
GetComparedTextHandler
public class GetComparedTextHandler : IRequestHandler<GetComparedTextQuery, ComparedDraftDto>
{
private readonly AppDbContext _appDbContext;
private readonly TpaChannel _tpaChannel;
public GetComparedTextHandler(AppDbContext appDbContext, TpaChannel tpaChannel)
{
_appDbContext = appDbContext;
_tpaChannel = tpaChannel;
}
public async Task<ComparedDraftDto> Handle(GetComparedTextQuery request, CancellationToken cancellationToken)
{
var edDraftComparison = ...// get compared text from repository
if (edDraftComparison == null) {
Repository doesn't have record yet.
// 1) Adding to repository request.InitialDraftId, request.DraftId
.........
// 2) Create Channel for background Service
message = "added_to_queue";
var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
cts.CancelAfter(TimeSpan.FromSeconds(180)); // wait max seconds
var versionDto = new VersionDto(request.InitialDraftId, request.DraftId, request.CurrVer, request.PrevVer);
await _tpaChannel.AddVersionsAsync(versionDto, cts.Token);
} // if (edDraftComparison == null)
else {...}
return ....
}
处理程序向控制器和 Web 客户端发送响应。但毕竟 tpaChannel 启动后台服务。它更新了存储库中的一条记录(通过 InitialDraftId)。
然后我需要使用 SignalR 获取更新的记录。
我读了教程,控制器动作可以加载signalR:
hubContext.Clients.User(UserId).SendAsync(
"receiveUpdatedText",
new Article<LikeRelatedPayload>
{
DraftId = draftId,
Payload = payload
}
);
但这是错误的想法,因为我必须在后台服务工作后从存储库中获取记录。
我需要在哪里创建一个 singnalR 服务,它将记录从后台服务发送给当前用户?
对不起语言,我很难用英语解释情况。
解决方案
IHubContext
在你相应的后台服务中使用如何。我不知道我们的后台服务是什么样的......所以我只描述一些虚拟的
public abstract class DummyProcessor : Microsoft.Extensions.Hosting.BackgroundService
{
IHubContext<MyHub> _myHub;
protected DummyProcessor(IHubContext<MyHub> myHub)
{
ServiceScopeFactory = serviceScopeFactory;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
// some logic...
await _myHub.Clients.All.SendAsync("As we usually do");
}
}
推荐阅读
- apache-spark - 在 pySpark 中旋转具有数值和分类值的两列
- ios - 如何使用 MFi 和外部附件框架以编程方式重新连接 IOS 上的 Classic Bluetooh
- reactjs - 使用 react-native 模拟 iPhone 位置(假 GPS)
- oracle - Oracle 11.2.0.1(32 位)给出 ORA-12547: TNS:lost contact while creating DB with dbca
- c# - 如何获取 xaml 的内容
在 .cs 中? - asp.net-core - 如何在 IIS 上部署 beta 版本?
- python - 如何遍历 Python 列表及其列表元素,在每个元素中拆分字符串并写出新列表
- python - 带有 2 个定义相同方法的 Mixin 的 CBV - 如何让每个 Mixin 执行自己的代码?
- html - 将“https:”附加到以 src=// 开头的汤中的链接
- php - Cakephp 3 - 使用文件上传将大型 CSV 导入数据库 错误 503 服务不可用