我有一个连接到数字秤的系统,我正在尝试使用 SignalR 将重量传递给其他请求客户端。
我的集线器如下所示:
public class ScaleHub : Hub
{
    private static string ScaleClientId { get; set; }
    // the weight object for the client making the request
    private static Dictionary<string, WeightDTO> scaleWeights =
        new Dictionary<string, WeightDTO>();
    public void RegisterScale()
    {
        ScaleClientId = Context.ConnectionId;
    }
    public WeightDTO GetWeight()
    {
        // clear the scale weight for the client making the request
        scaleWeights[Context.ConnectionId] = null;
        Task updateWeightTask = Clients[ScaleClientId].UpdateWeight(Context.ConnectionId);
        // this doesn't wait :-(
        updateWeightTask.Wait();
        return scaleWeights[Context.ConnectionId];
    }
    public void UpdateWeight(WeightDTO weight, string clientId)
    {
        // update the weight for the client making the request
        scaleWeights[clientId] = weight;
    }
}
客户端的重要部分是:
scaleHub.On<string>("UpdateWeight", UpdateWeight);
private void UpdateWeight(string clientId)
{
    // this is replaced with code that talks to the scale hardware
    var newWeight = new WeightDTO(123, WeightUnitTypes.LB);
    scaleHub.Invoke("UpdateWeight", newWeight, clientId).Wait();
}
public Task<WeightDTO> GetWeight()
{
    return scaleHub.Invoke<WeightDTO>("GetWeight");
}
我还是 SignalR 的新手,所以我不确定我是否以正确的方式进行。
添加Thread.Sleep(2000)而不是updateWeightTask.Wait()解决问题,因为它为 UpdateWeight 的往返调用提供了足够的时间来完成。我不想让我的客户等待 2 秒来称重。
有什么建议么?