/// <summary> /// Creates a connection for a remote endpoint. /// </summary> /// <param name="context">The listener context to use.</param> /// <param name="remote">The endpoint to connect to.</param> public static Task <Connection> ConnectAsync(ListenerContext context, IPEndPoint remote) { var tcs = new TaskCompletionSource <Connection>(); context.Thread.PostAsync((state) => { var socket = new UvTcpHandle(); try { socket.Init(context.Thread.Loop, context.Thread.QueueCloseHandle); socket.NoDelay(true); socket.Connect(context.Thread.Loop, ServiceAddress.FromIPEndPoint(remote), (request, status, ex, sender) => { request.Dispose(); if (ex != null) { // Error has occured, set the exception socket.Dispose(); tcs.SetException(ex); return; } // Create the connection and notify var connection = new Connection(context, socket); tcs.SetResult(connection.Start() ? connection : null); }, tcs); } catch (UvException ex) { //Service.Logger.Log(ex); socket.Dispose(); tcs.SetException(ex); } }, tcs); return(tcs.Task); }