SignalR 连接(集线器代理)生命周期
SignalR connection (hub proxy) lifetime
将客户端连接到 SignalR hub 的最佳做法是什么?在客户端中,是在某处保持连接(集线器代理)更好,还是为每个集线器方法调用创建连接(集线器代理)更好?
最佳方法是只为所有方法调用保留一个连接。您打开的每个新连接都会浪费网络资源和处理,因为 SignalR 需要为每个连接与服务器保持实时连接。这意味着移动设备的电池耗尽和更多的服务器工作负载。
[更新]
阅读@alex-dresko 的回答后,我意识到我的回答需要一些澄清。
在同一个连接下创建多少代理并不重要,它不会改变性能:
hubConnection = new HubConnection(BASE_ADDRESS);
var chatProxy = hubConnection.CreateHubProxy("chatHub");
var otherProxy = hubConnection.CreateHubProxy("otherHub");
var nProxy = hubConnection.CreateHubProxy("nHub");
但是,您问的是
is it better to keep connection (hub proxy) somewhere
嗯,连接是一回事 (HubConnection
),代理是另一回事。
新连接将在客户端和服务器之间打开一个新的桥梁,因此在您的应用程序中全局创建和持久化单个连接是有意义的。然后您可以重复使用同一个连接来创建任意数量的代理。
您可以轻松测试此场景。创建一个创建连接和 2 个代理中心的控制台应用程序。然后在每个连接上创建 2 个连接和 1 个集线器并检查信号器日志...
每 https://www.asp.net/signalr/overview/guide-to-the-api/hubs-api-guide-server#multiplehubs
There is no performance difference for multiple Hubs compared to
defining all Hub functionality in a single class.
是否使用多个集线器只是决定如何逻辑组织代码的问题。标准 OOP 实践适用于此。
稍后在同一文档中...
If you need to use the context multiple-times in a long-lived object,
get the reference once and save it rather than getting it again each
time. Getting the context once ensures that SignalR sends messages to
clients in the same sequence in which your Hub methods make client
method invocations. For a tutorial that shows how to use the SignalR
context for a Hub, see Server Broadcast with ASP.NET SignalR.
...不确定最后一点是否与您的要求相关,但在您规划信号器架构时了解一下是件好事。
将客户端连接到 SignalR hub 的最佳做法是什么?在客户端中,是在某处保持连接(集线器代理)更好,还是为每个集线器方法调用创建连接(集线器代理)更好?
最佳方法是只为所有方法调用保留一个连接。您打开的每个新连接都会浪费网络资源和处理,因为 SignalR 需要为每个连接与服务器保持实时连接。这意味着移动设备的电池耗尽和更多的服务器工作负载。
[更新]
阅读@alex-dresko 的回答后,我意识到我的回答需要一些澄清。 在同一个连接下创建多少代理并不重要,它不会改变性能:
hubConnection = new HubConnection(BASE_ADDRESS);
var chatProxy = hubConnection.CreateHubProxy("chatHub");
var otherProxy = hubConnection.CreateHubProxy("otherHub");
var nProxy = hubConnection.CreateHubProxy("nHub");
但是,您问的是
is it better to keep connection (hub proxy) somewhere
嗯,连接是一回事 (HubConnection
),代理是另一回事。
新连接将在客户端和服务器之间打开一个新的桥梁,因此在您的应用程序中全局创建和持久化单个连接是有意义的。然后您可以重复使用同一个连接来创建任意数量的代理。
您可以轻松测试此场景。创建一个创建连接和 2 个代理中心的控制台应用程序。然后在每个连接上创建 2 个连接和 1 个集线器并检查信号器日志...
每 https://www.asp.net/signalr/overview/guide-to-the-api/hubs-api-guide-server#multiplehubs
There is no performance difference for multiple Hubs compared to defining all Hub functionality in a single class.
是否使用多个集线器只是决定如何逻辑组织代码的问题。标准 OOP 实践适用于此。
稍后在同一文档中...
If you need to use the context multiple-times in a long-lived object, get the reference once and save it rather than getting it again each time. Getting the context once ensures that SignalR sends messages to clients in the same sequence in which your Hub methods make client method invocations. For a tutorial that shows how to use the SignalR context for a Hub, see Server Broadcast with ASP.NET SignalR.
...不确定最后一点是否与您的要求相关,但在您规划信号器架构时了解一下是件好事。