Code analysis complains that an object can be deleted more than once. What for?

I get a warning about responseStream in the following function:

 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; } 

I call this function from places like this:

 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
source share
1 answer

StreamReader takes control of the stream passed to it in the constructor call, in the sense that it will call Dispose on it when the StreamReader itself is closed, so it will already be deleted when the external Using statement tries to get rid of it.

+5
source

Source: https://habr.com/ru/post/1416005/


All Articles