代码分析抱怨对象可以被多次处理。为什么?

时间:2012-06-04 17:10:45

标签: c# .net code-analysis

我在以下功能中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;
            }

1 个答案:

答案 0 :(得分:5)

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