Exemplo n.º 1
0
        public static Task ConnectAsync(this Socket socket, IPEndPoint endPoint, int timeoutMSec = -1)
        {
            var tcs = new TaskCompletionSource <bool>();

            var asyncResult = socket.BeginConnect(endPoint, ar =>
            {
                try
                {
                    socket.EndConnect(ar);
                    tcs.TrySetResult(true);
                }
                catch (OperationCanceledException)
                {
                    tcs.TrySetCanceled();
                }
                catch (Exception e)
                {
                    tcs.TrySetException(e);
                }
                finally
                {
                    if (timeoutMSec > 0)
                    {
                        TimeoutHandler.Unregister(tcs);
                    }
                }
            }, tcs);

            RegisterForTimeout(tcs, timeoutMSec, socket, asyncResult);

            return(tcs.Task);
        }