首页 > 解决方案 > 带有信号器集线器方法的异步/等待

问题描述

所以我已经开始为“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     

    }

标签: c#asynchronousasync-awaitsignalr

解决方案


使用的唯一原因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,因为:

  1. 如果发生未处理的异常,它可能会使您的应用程序崩溃(阅读thisthis),因此您必须确保在任何可能引发异常的地方放置try/块,并且catch
  2. 无论调用什么,它都不能等到它完成。

由于第 2 点,我在使用asyncSignalR 的事件处理程序时遇到了麻烦。因为 SignalR 不能等待您的async方法完成,它可能会在第一个请求完成之前开始处理另一个请求。这对你来说可能是也可能不是问题。

这对我来说是个问题,所以我让我的事件处理程序保持同步。


推荐阅读