سؤال

I'm having some trouble using the StreamWriter class correctly. I have about 10 objects I need to post, but only a couple at a time at most. However, after 2 posts, the third does not go through and times out. I realize this is because the max connections you can have is 2. However, I'm confused as to why I am being stopped after 2 since I (think) I am closing my StreamWriter connection. Here is my code:

var httpWebRequest = (HttpWebRequest)WebRequest.Create("my url"); 
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
//var data = json data

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    streamWriter.Write(data);
    streamWriter.Close();
}

I thought the using statement would close it automatically, but it didn't, so I added the Close() line. However, this didn't seem to do anything. The debugger gets stuck on the using line on the third try. If I setServicePointManager.DefaultConnectionLimit to something like 10, everything works, but I'm confused why what I have written doesn't. Any help would be appreciated!

هل كانت مفيدة؟

المحلول

I suspect it's more likely that it's to do with what you do with the response.

The using statement will close the StreamWriter, and you don't even need the explicit Close call. However, you also need a using statement for the response:

using (var response = httpWebRequest.GetResponse())
{
    ...
}

If you don't have that, the connection pool for the particular host will be clogged with connections due to unclosed response.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top