我有一个连接到数字秤的系统,我试图使用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秒才能获得体重。
有什么建议吗?