我得到連續 [不停]從網頁的url mesages:無法關閉的StreamReader(reader.Close();塊碼)
string webUrl = "xxxxx/status.cgi";
WebClient client = new WebClient();
client.Credentials = new NetworkCredential("UUU", "PPP");
StreamReader reader = new StreamReader(client.OpenRead(webUrl), Encoding.UTF8,true);
string line;
int counter = 0;
while ((line = reader.ReadLine()) != null)
{
if(line == "XXXXXX")
{
break;
}
}
Console.WriteLine("Try to Close Stream Reader...");
reader.Close();
Console.WriteLine("Stream Reader is closed...");
的問題是,當我從while循環打破,我想關閉流式閱讀器...但流式閱讀器不關閉....「reader.Close();」掛起/阻止代碼...
爲什麼會發生這種情況?如何解決它?
UPDATE: 「使用」不工作在我的情況:退出循環,但流讀取器沒有設置...航/砌塊
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Linq;
using System.Text;
namespace TestStreamReader
{
class Program
{
static void Main(string[] args)
{
string webUrl = "http://X.Y.Z:7000/status.cgi";
int counter = 0;
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential("admin", "000000");
using (StreamReader reader = new StreamReader(client.OpenRead(webUrl), Encoding.UTF8, true))
{
string line;
while ((line = reader.ReadLine()) != null)
{
counter++;
Console.WriteLine("Input"+ line);
if (counter == 10)
{
Console.WriteLine("I am exiting the loop");
break;
}
}
Console.WriteLine("Exit the while loop");
}
Console.WriteLine("Reader should be desposed");
}
Console.WriteLine("Web Client should be disposed!");
}
}
}
先關閉webclient? – 2012-07-31 14:20:57
您是否收到錯誤或異常?如果是這樣,那是什麼? – Kevin 2012-07-31 14:23:56
WebClient沒有「關閉方法」...但我做了同樣的HttpWebResponse具有接近的方法...不改變任何東西... – Novalis 2012-07-31 14:24:55