1

我的应用程序需要执行很多不同的请求(每秒约 1-2 个)。我有一种连续运行的请求(RequestMade -> ResponseReceived -> RequestMade -> ...)。

如果我进入另一个屏幕,只要我留在那个屏幕上,我就应该开始一组新的请求以连续运行。

问题是新的一组请求(the initial request) is delayed with ~ 1 minute

下面发布了用于执行请求的代码。

请注意,此行在 12:00 打印到控制台:

Debug.WriteLine("Writing RequestStream ("+_request.GetType().FullName + " | " + DateTime.Now.ToLocalTime()+")");

和行:

 Debug.WriteLine("Request is posting.....(" + _request.GetType().FullName + " | " + DateTime.Now.ToLocalTime()+")");

 Debug.WriteLine("Reading ResponseStream (" + _request.GetType().FullName + " | " + DateTime.Now.ToLocalTime() + ")");

在 12:01 打印(1 分钟后....)

private class RequestResponseTask
        {
            private Uri _uri = null;
            private string _uriAddress = null;
            private WebRequest _webRequest = null;
            private ARequest _request = null;
            private JsonTextParser _parser = null;
            private RequestState _requestState = null;

            public RequestResponseTask(ARequest request)
            {
                // uri address
                _uriAddress = CVSCustomRelease.Instance.ReleaseSettings.SelectedPrivateLabel.GetServer(LoginSettings.Instance.SelectedServer).Address
                    + CONTEXTUAL_REQUEST_PATH;
                // uri
                _uri = new Uri(_uriAddress);

                // request
                _request = request;
                _parser = new JsonTextParser();
                _requestState = new RequestState(_request);
            }

            public void StartRequest()
            {
                Debug.WriteLine("Starting RUN.......(" + _request.GetType().FullName + " | " + DateTime.Now.ToLocalTime() + ")");
                Task.Factory.StartNew(() =>
                    {
                        Debug.WriteLine("RUN Started. - for "+_request.GetType().FullName + " | " + DateTime.Now.ToLocalTime());
                        _request.ResponseReceived = false;
                        Debug.WriteLine("Before WebRequest ("+_request.GetType().FullName + " | " + DateTime.Now.ToLocalTime()+")");
                            _webRequest = WebRequest.Create(_uri);

                        Debug.WriteLine("after WebRequest (" + _request.GetType().FullName + " | " + DateTime.Now.ToLocalTime() + ")");
                        _webRequest.ContentType = "text/x-gwt-rpc;charset=utf-8";
                        _webRequest.Method = "Post";

                        _requestState.Request = _webRequest;

                        // Start the Asynchronous 'BeginGetRequestStream' method call.    
                        Debug.WriteLine("Writing RequestStream ("+_request.GetType().FullName + " | " + DateTime.Now.ToLocalTime()+")");
                        IAsyncResult r = (IAsyncResult)_webRequest.BeginGetRequestStream(
                            new AsyncCallback(PostRequest), _requestState);

                        _requestState.ResetEvent.WaitOne();
                        Debug.WriteLine("Reading ResponseStream (" + _request.GetType().FullName + " | " + DateTime.Now.ToLocalTime() + ")");

                        IAsyncResult asyncResp = (IAsyncResult)_webRequest.BeginGetResponse(
                            new AsyncCallback(ReadResponse), _requestState);
                    });
            }

            private void PostRequest(IAsyncResult asynchronousResult)
            {
                Debug.WriteLine("======================================================");
                Debug.WriteLine("Request is posting.....(" + _request.GetType().FullName + " | " + DateTime.Now.ToLocalTime()+")");

                // End the Asynchronus Request.
                Stream streamResponse = _webRequest.EndGetRequestStream(asynchronousResult);

                ARequest request = _requestState.OriginalRequest;
                request.UpdateTimestampRealtime();
                string postData = request.GetPostData();

                EventsLog.Instance.WriteEvent("Request: " + postData);

                // Create a string that is to be posted to the uri.
                // Convert the string into a byte array. 
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);

                EventsLog.Instance.CurrentSession.AddTraficAmount(TraficType.Outgoing, byteArray.Length);

                // Write the data to the stream.
                streamResponse.Write(byteArray, 0, postData.Length);
                streamResponse.Flush();
                Debug.WriteLine("Request POSTED.");
                Debug.WriteLine("======================================================");
                _requestState.ResetEvent.Set();
            }

            private async void ReadResponse(IAsyncResult asyncResult)
            {
                _requestState = (RequestState)asyncResult.AsyncState;
                WebRequest myWebRequest = _requestState.Request;

                WebResponse response = (WebResponse)myWebRequest.EndGetResponse(asyncResult);
                Stream responseStream = response.GetResponseStream();

                StreamReader streamRead = new StreamReader(responseStream);

                string responseString = await streamRead.ReadToEndAsync();

                byte[] byteArray = Encoding.UTF8.GetBytes(responseString);
                EventsLog.Instance.CurrentSession.AddTraficAmount(TraficType.Incomming, byteArray.Length);

                // build response object
                JsonObject jsonObject = _parser.Parse(responseString);
                EventsLog.Instance.WriteEvent("Response: " + jsonObject.ToString() + "\nFor Request: " + _requestState.OriginalRequest.RequestId + " | " +_requestState.OriginalRequest.GetType().FullName);

                _requestState.ResetEvent.Reset();

                // notify listeners
                _requestState.OriginalRequest.ResponseReceived = true;
                _requestState.OriginalRequest.NotifyResponseListeners(jsonObject as JsonObjectCollection);
            }
        }

执行请求:

 new RequestResponseTask(_request).StartRequest();
4

1 回答 1

1

我的猜测:您的代码阻塞,这导致另一个线程超时(这是 1 分钟的来源),然后导致解除阻塞第一个线程。

您的代码中有 BeginGetRequestStream 和 ResetEvent.WaitOne 之类的东西 - 在像您这样的 Windows 应用商店代码中不应该需要这些东西。尝试改用 WebClient 的异步方法或 HttpClient。使用等待而不是 WaitOne。

于 2013-10-21T14:38:08.677 回答