我有一个大约在同一时间启动的tcp服务器和客户端,但是在客户端尝试连接到服务器时,服务器可能还没有启动。客户端此时不应该失败,但经过一段时间的延迟后重试连接达到某个限制。下面的解决方案可行,但在我无法控制的线程上放置一个Thread.Sleep这样的异常处理程序似乎是错误的。有更好的方法吗?
这是旧版本的.Net,因此我无法使用async关键字和Task类。
// Starts the client
public void Start(
int connectRetryAttempts,
int connectRetryDelay)
{
this.connectRetryAttempts = connectRetryAttempts;
this.connectRetryDelay = connectRetryDelay;
tcpClient.BeginConnect(EndPoint.Address, EndPoint.Port, ConnectCallback, null);
State = States.Connecting;
}
// Handles BeginConnect completion
private void ConnectCallback(IAsyncResult asyncResult)
{
try
{
tcpClient.EndConnect(asyncResult);
}
catch (Exception ex)
{
if (connectRetryAttempts > 0)
{
--connectRetryAttempts;
Thread.Sleep(connectRetryDelay * 1000);
tcpClient.BeginConnect(EndPoint.Address, EndPoint.Port, ConnectCallback, null);
}
else
{
State = States.Disconnected;
Log.LogErrorFormat("Exception encountered trying to connect: {0}", ex);
}
return;
}
State = States.Connected;
buffer = new byte[BufferSize];
networkStream = tcpClient.GetStream();
networkStream.BeginRead(buffer, 0, buffer.Length, ReadCallback, null);
}
答案 0 :(得分:1)
您可以使用Timer
if (connectRetryAttempts > 0)
{
--connectRetryAttempts;
Timer delay = null;
delay = new Timer(_=>
{
tcpClient.BeginConnect(EndPoint.Address, EndPoint.Port, ConnectCallback, null);
delay.Dispose();
}, connectRetryDelay * 1000, Timeout.Infinite);
}
将间隔设置为Timeout.Infinite
时,计时器将仅触发一次。