4

responseStream我在以下功能中收到警告:

private static string GetResponseString(WebResponse response)
        {
            using (var responseStream = response.GetResponseStream())
            {
                if (responseStream != null)
                {
                    using (var responseReader = new StreamReader(responseStream))
                    {
                        var strResponse = responseReader.ReadToEnd();
                        return strResponse;
                    }
                }
            }

            return string.Empty;
        }

我从像这样的地方调用这个函数:

var request = (HttpWebRequest)WebRequest.Create(Uri);
            request.Headers.Add("Authorization", "GoogleLogin auth=" + this.SecurityToken);
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "POST";
            request.Timeout = 5000;

            // build the post string     
            var postString = new StringBuilder();
            postString.AppendFormat("registration_id={0}", recipientId);
            postString.AppendFormat("&data.payload={0}", message);
            postString.AppendFormat("&collapse_key={0}", collapseKey);

            // write the post-string as a byte array     
            var requestData = Encoding.ASCII.GetBytes(postString.ToString());
            request.ContentLength = requestData.Length;
            var requestStream = request.GetRequestStream();
            requestStream.Write(requestData, 0, requestData.Length);
            requestStream.Close();

            // Do the actual request and read the response stream  
            try
            {
                var response = request.GetResponse();
                var responseString = GetResponseString(response);
                response.Close();

                return responseString.Contains("id=") 
                    ? SendStatus.Ok 
                    : GetSendStatusFromResponse(responseString);
            }
            catch (WebException ex)
            {
                var webResponse = (HttpWebResponse)ex.Response;
                if (webResponse != null)
                {
                    if (webResponse.StatusCode.Equals(HttpStatusCode.Unauthorized))
                    {
                        return SendStatus.Unauthorized;
                    }

                    if (webResponse.StatusCode.Equals(HttpStatusCode.ServiceUnavailable))
                    {
                        return SendStatus.ServiceUnavailable;
                    }
                }

                this.LoggerService.Log(null, ex);
                return SendStatus.GeneralException;
            }
4

1 回答 1

5

StreamReader 在构造函数调用中获取传递给它的流的所有权,因为它会在 StreamReader 本身关闭时对其调用 Dispose - 因此,当外部 Using 语句尝试处置它时,它已经被处置。

于 2012-06-04T17:14:48.910 回答