我已阅读 this post
In some applications you might want to automatically re-establish a connection after it has been lost and the attempt to reconnect has timed out. To do that, you can call the Start method from your Closed event handler (disconnected event handler on JavaScript clients). You might want to wait a period of time before calling Start in order to avoid doing this too frequently when the server or the physical connection are unavailable. The following code sample is for a JavaScript client using the generated proxy.
当我从 Closed 事件调用 Start 方法时
connection.Closed += connection_Closed;
static void connection_Closed()
{
Console.WriteLine("connection closed");
ServerConnection.Start().Wait();
}
发生异常:
连接尚未建立。
我希望它一直持续到服务器正常时它成功。不要抛出异常。我如何达到这一点。
有任何想法吗?
谢谢
最佳答案
与凤凰的答案的不同之处:
OnDisconnected
实际上是必需的,因为 Closed
连接失败时触发事件 代码:
private HubConnection _hubConnection = null;
private IHubProxy _chatHubProxy = null;
private void InitializeConnection()
{
if (_hubConnection != null)
{
// Clean up previous connection
_hubConnection.Closed -= OnDisconnected;
}
_hubConnection = new HubConnection("your-url");
_hubConnection.Closed += OnDisconnected;
_chatHubProxy = _hubConnection.CreateHubProxy("YourHub");
ConnectWithRetry();
}
void OnDisconnected()
{
// Small delay before retrying connection
Thread.Sleep(5000);
// Need to recreate connection
InitializeConnection();
}
private void ConnectWithRetry()
{
// If this fails, the 'Closed' event (OnDisconnected) is fired
var t = _hubConnection.Start();
t.ContinueWith(task =>
{
if (!task.IsFaulted)
{
// Connected => re-subscribe to groups etc.
...
}
}).Wait();
}
关于client - SignalR .Net 客户端 : how to re-establish a connection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17438428/