c# - 带有信号器集线器方法的异步/等待
问题描述
所以我已经开始为“x”应用程序开发 uber。与优步相同的概念。以下代码是我的 Signalr hub 上的代码。我使用信号器在客户端和服务器之间进行通信。因此,当客户端请求帮助时,它会连接到 RequestForHelp。然后 RequestForHelp 将请求发送回正确的供应商。根据供应商的回答,HelpResponseYes HelpResponseNo 被调用。我想让它成为异步的。我想让请求帮助成为一项任务。因此,当我单击请求按钮时,程序会等待。有什么建议可以做到吗?
public void RequestForHelp(RequestDetails requestDetails, Location customerClientLocation, int customerClientId)
{
Customer Customer = Service.CustomerService.GetCustomerById(requestDetails.CustomerId);
Customer.ClientId = customerClientId;
Customer.ClientLocation = customerClientLocation;
requestDetails.Customer = Customer;
Clients.User(requestDetails.NearestSupplierList.FirstOrDefault().AspNetUserID).requestForHelpInClient(requestDetails);
}
public void HelpResponseYes(RequestDetails requestDetails)
{
//A supplier is matched
}
public void HelpResponseNo(RequestDetails requestDetails)
{
//next supplier on the list
}
解决方案
使用的唯一原因async
是如果您有需要await
。因此,我假设您将进行requestForHelpInClient
异步并返回 a Task
,并且可以await
做到。
就这么简单:
public async void RequestForHelp(RequestDetails requestDetails, Location customerClientLocation, int customerClientId)
{
Customer Customer = Service.CustomerService.GetCustomerById(requestDetails.CustomerId);
Customer.ClientId = customerClientId;
Customer.ClientLocation = customerClientLocation;
requestDetails.Customer = Customer;
await Clients.User(requestDetails.NearestSupplierList.FirstOrDefault().AspNetUserID).requestForHelpInClient(requestDetails);
}
然而,当你看到 时,你总是要认真思考async void
,因为:
由于第 2 点,我在使用async
SignalR 的事件处理程序时遇到了麻烦。因为 SignalR 不能等待您的async
方法完成,它可能会在第一个请求完成之前开始处理另一个请求。这对你来说可能是也可能不是问题。
这对我来说是个问题,所以我让我的事件处理程序保持同步。
推荐阅读
- reactjs - 在不改变方向的情况下反应 Native Expo 方向监听器
- c# - C# 不识别变量
- javascript - Ajax 在 codeigniter 中获取多个值
- java - AndroidStudio - 片段中的绑定服务
- javascript - 为什么在此快速排序期间超出了我的调用堆栈大小?
- algorithm - 如果它们需要 O(n) 时间对列表进行排序,为什么我们不使用尝试进行排序?
- sparql - 为什么此 wikidata 查询不选择荷兰省份
- php - 为什么我的 PHP 表单在我的电子邮件客户端中显示不同的名称?
- c - 使用优化编译会导致条件错误
- symfony - 在 api 平台中验证嵌入式模型