Ejemplo n.º 1
0
        public async Task <bool> Connect()
        {
            WebSocket = new WebSocket(Url);
            WebSocket.ConnectAsync();

            WebSocket.OnMessage += OnWebSocketMessage;

            TaskCompletionSource <bool> result = new TaskCompletionSource <bool>();

            EventHandler success = null;
            EventHandler <ErrorEventArgs> error = null;
            DelayedAction Timeout = null;

            Action unregisterActions = () =>
            {
                WebSocket.OnOpen  -= success;
                WebSocket.OnError -= error;
                Timeout.Abort();
            };

            WebSocket.OnOpen += success = (sender, args) =>
            {
                unregisterActions();

                result.SetResult(true);
            };
            WebSocket.OnError += error = (sender, args) =>
            {
                unregisterActions();

                result.SetResult(false);
            };
            Timeout = new DelayedAction(() =>
            {
                unregisterActions();

                result.SetResult(false);
            });
            Timeout.Run(3000); // 3 second timeout

            await result.Task;

            return(result.Task.Result);
        }