使 SignalR 客户端连接保持活动状态
keeping SignalR client connection alive
如果我的 SignalR 客户端连接断开,我希望客户端尝试重新连接。这是实现这个的好模式吗?我指的是通过重新启动连接来处理 SignalR 连接上的 Closed 事件。
public class OnPremiseWebHubClient
{
private HubConnection _hubConnection;
private IHubProxy _hubProxy;
private OnPremiseWebHubClient() { }
static OnPremiseWebHubClient() { }
private static readonly OnPremiseWebHubClient _instance = new OnPremiseWebHubClient();
public static OnPremiseWebHubClient Instance { get { return _instance; } }
public async Task Start()
{
_hubConnection = new HubConnection("http://OnPremiseWeb/");
_hubProxy = _hubConnection.CreateHubProxy("OnPremiseHub");
// IS THIS A GOOD PATTERN FOR KEEPING THE CONNECTION ALIVE?
_hubConnection.Closed += async () =>
{
// reconnect if we close
await _hubConnection.Start();
};
await _hubConnection.Start();
}
}
SignalR 有自己的重新连接机制。但经过一些重试后,状态将变为 disconnected/Closed。 Disconnected/Closed state 表示 signalr 尝试重新连接但无法连接。所以这是在那里应用重新连接以连续重新连接的好地方。
有一个缺点:在移动设备上重新连接会耗电。
您可以查看 here 了解更多详情。
如果我的 SignalR 客户端连接断开,我希望客户端尝试重新连接。这是实现这个的好模式吗?我指的是通过重新启动连接来处理 SignalR 连接上的 Closed 事件。
public class OnPremiseWebHubClient
{
private HubConnection _hubConnection;
private IHubProxy _hubProxy;
private OnPremiseWebHubClient() { }
static OnPremiseWebHubClient() { }
private static readonly OnPremiseWebHubClient _instance = new OnPremiseWebHubClient();
public static OnPremiseWebHubClient Instance { get { return _instance; } }
public async Task Start()
{
_hubConnection = new HubConnection("http://OnPremiseWeb/");
_hubProxy = _hubConnection.CreateHubProxy("OnPremiseHub");
// IS THIS A GOOD PATTERN FOR KEEPING THE CONNECTION ALIVE?
_hubConnection.Closed += async () =>
{
// reconnect if we close
await _hubConnection.Start();
};
await _hubConnection.Start();
}
}
SignalR 有自己的重新连接机制。但经过一些重试后,状态将变为 disconnected/Closed。 Disconnected/Closed state 表示 signalr 尝试重新连接但无法连接。所以这是在那里应用重新连接以连续重新连接的好地方。
有一个缺点:在移动设备上重新连接会耗电。
您可以查看 here 了解更多详情。