C# 无法从传输连接读取数据:控制台应用程序中的连接已关闭错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11323584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unable to read data from the transport connection: The connection was closed error in console application
提问by Darshana
I have this code in console application and it runs in a loop
我在控制台应用程序中有此代码,它在循环中运行
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(search);
request.Headers.Add("Accept-Language", "de-DE");
request.Method = "GET";
request.Accept = "text/html";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(),
Encoding.ASCII))
{
string html = reader.ReadToEnd();
FindForMatch(html, url);
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
after few loops it gives
经过几次循环后,它给出
Unable to read data from the transport connection: The connection was closed
无法从传输连接读取数据:连接已关闭
error. any idea why this happen? thanx..
错误。知道为什么会这样吗?谢谢..
采纳答案by Darshana
After adding
添加后
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
it works fine..
它工作正常..
I found it form this blog post
我从这篇博文中找到了它
WebRequest and Unable to read data from the transport connection Error
回答by Michael
I just tried the code, looping 10 times to load google.com and it worked for me. Is there something special about search- perhaps try replacing it with another uri. I did not include findForMatch- I assume it is not doing anything that would cause the exception.
我只是尝试了代码,循环 10 次以加载 google.com,它对我有用。有什么特别之处search- 也许尝试用另一个 uri 替换它。我没有包括findForMatch- 我认为它没有做任何会导致异常的事情。
回答by JohnnBlade
Try disposing the reader in the finally block of your try catch
尝试在 try catch 的 finally 块中处理读取器

