示例#1
0
        private void HandleApiResponse(JToken data)
        {
            if (data == null && data.Children().Count() != 2)
            {
                return;
            }

            var idToken = data.SelectToken("id");

            if (idToken == null)
            {
                throw new Exception("response id not found.");
            }

            string id = idToken.ToObject <string>();

            TaskCompletionSource <JToken> openTask;

            if (!OpenTasks.TryGetValue(id, out openTask))
            {
                return;
            }

            OpenTasks.Remove(id);
            OpenTaskTimes.Remove(id);

            openTask.SetResult(data.SelectToken("result"));
        }
        private void TimeoutOpenTasksCheck()
        {
            while (Socket.State == WebSocketState.Open)
            {
                var now   = DateTime.Now;
                int count = 0;

                foreach (var ttKey in OpenTaskTimes.Keys)
                {
                    if ((now - OpenTaskTimes[ttKey]).TotalMilliseconds >= TimeoutMS)
                    {
                        TaskCompletionSource <JToken> openTask = OpenTasks[ttKey];

                        OpenTasks.Remove(ttKey);
                        OpenTaskTimes.Remove(ttKey);

                        openTask.SetResult(JToken.FromObject(new ApiError()
                        {
                            Code    = "0",
                            IsError = "true",
                            Message = "Request timeout."
                        }));
                    }

                    //sleep checking each 10 requests
                    if ((count % 10) == 0)
                    {
                        Thread.Sleep(1000);
                    }

                    count++;
                }
            }
        }