2

我正在开发一个连接尝试超时应该是可配置的应用程序。

如果你看一下下面的代码,你会意识到我正在尝试做:等待 20 毫秒(此时它是硬编码的),如果可以建立连接,则调用 onConnected 回调操作为 true;否则为 false (例如,如果发生超时)

internal void Connect(Action<bool> onConnected)
{
    Func<AsyncCallback, object, IAsyncResult> beginConnect =
        (callback, s) =>
            {
                var asyncResult = _socket.BeginConnect(Endpoint, callback, s);
                var success = asyncResult.AsyncWaitHandle.WaitOne(20, true);
                if(!success) throw new TimeoutException("Connection timeout");
                return asyncResult;
            };

    var task = Task.Factory.FromAsync(beginConnect, _socket.EndConnect, this);
    task.ContinueWith(t => onConnected(true), TaskContinuationOptions.NotOnFaulted)
        .ContinueWith(t => onConnected(false), TaskContinuationOptions.OnlyOnFaulted);
    task.ContinueWith(t => onConnected(false), TaskContinuationOptions.OnlyOnFaulted);
}

问题是由于 beginConnect 函数中的超时异常,从未调用过回调。我想我可以在 Connect 方法调用者中用 tyr-catch 语句包装调用,但它可以有多个调用者,并且在每个调用者看起来都错误时这样做。

我怎样才能达到我想要的?

4

1 回答 1

0

我找到了一种方法来实现我正在寻找的东西:

internal void Connect(Action<bool> onConnected)
{
    Func<AsyncCallback, object, IAsyncResult> beginConnect =
        (callback, s) => 
            {
                var asyncResult = _socket.BeginConnect(Endpoint, callback, s);
                var success = asyncResult.AsyncWaitHandle.WaitOne(20, true);
                if(!success)
                {
                    onConnected(false);
                    return default(IAsyncResult);
                }
                return asyncResult;
            };

    var task = Task.Factory.FromAsync(beginConnect, _socket.EndConnect, this);
    task.ContinueWith(t => onConnected(true), TaskContinuationOptions.NotOnFaulted)
        .ContinueWith(t => onConnected(false), TaskContinuationOptions.OnlyOnFaulted);
    task.ContinueWith(t => onConnected(false), TaskContinuationOptions.OnlyOnFaulted);
}

关键是 20 毫秒后,如果还没有连接,它会调用带有 false 的回调并返回默认的 IAsyncResult。

于 2013-08-02T17:49:12.120 回答