Socket Beginconnect 在未连接的情况下为同一个套接字多次连接

Socket Beginconnect several times for the same socket while not connected

我正在尝试使用 c# 中的异步套接字将客户端连接到服务器。

我正在做socket.beginconnect尝试连接,重点是如果连接没有建立,我希望它尝试beginconnect,如果连接没有在500ms内建立,我想再试一次,比方说,10 次。

我尝试了一个简单的 bucle 但它不起作用,因为在上一个连接完成之前我无法再次开始连接,但是当 beginconnect 完成并且找不到服务器时,它 returns 一个期望没有服务器。

MSDN 文档说:

To cancel a pending call to the BeginConnect method, close the Socket. When the Close method is called while an asynchronous operation is in progress, the callback provided to the BeginConnect method is called. A subsequent call to the EndConnect method will throw an ObjectDisposedException to indicate that the operation has been cancelled.

所以每次都要新建一个Socket:

public Socket TryConnect(...)
{
    Socket socket;

    try
    {
        socket = new Socket(...);
        var connect = Task.Factory.FromAsync(
            socket.BeginConnect, socket.EndConnect, host, port, null);

        var isConnected = connect.Wait(TimeSpan.FromSeconds(0.5));

        if (!isConnected)
        {
            socket.Close();
            return null;
        }

        return socket;      
    }
    catch
    {
        if (socket != null)
        {
            socket.Dispose();
        }
        throw;
    }
}


for (var i = 0; i < 10; i++)
{
    var socket = TryConnect();
    if (socket != null)
        return socket;
}