namespace LEDServer
{
public class Weather
{
string weathervalue, weatherexplain, temperature;
int temp;
public void DoWork()
{
while (!_shouldStop)
{
try
{
getWeather();
}
catch (Exception e)
{
}
Thread.Sleep(5000);
}
Console.WriteLine("worker thread: terminating gracefully.");
}
public void RequestStop()
{
_shouldStop = true;
}
// Volatile is used as hint to the compiler that this data
// member will be accessed by multiple threads.
private volatile bool _shouldStop;
public static void startgetWeather()
{
Weather weather = new Weather();
Thread workerThread = new Thread(weather.DoWork);
// Start the worker thread.
workerThread.Start();
Console.WriteLine("main thread: Starting worker thread...");
// Loop until worker thread activates.
}
public void getWeather()
{
//weather data parsing
string sURL;
sURL = "http://api.openweathermap.org/data/2.5/weather?lat=37.56826&lon=126.977829&APPID=4cee5a3a82efa3608aaad71a754a94e0&mode=XML&units=metric" + "&dummy=" + Guid.NewGuid().ToString();
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(sURL);
myReq.Timeout = 10000;
myReq.Method = "GET";
StringBuilder output = new StringBuilder();
HttpWebResponse wRes = (HttpWebResponse)myReq.GetResponse();
Stream respGetStream = wRes.GetResponseStream();
StreamReader readerGet = new StreamReader(respGetStream, Encoding.UTF8);
XmlTextReader reader = new XmlTextReader(readerGet);
这个程序只工作两次getWeather()
。
我不知道为什么这个程序只能工作两次..
我制作了asyncsocket服务器并在Main Function中一起工作。
但它不起作用..这个问题是因为线程?
每个班级都不同......
答案 0 :(得分:5)
我不知道为什么这个程序只运行两次..
因为默认HTTP连接池的大小为每个主机2个连接 - 并且您同时使用它们。您可以使用app.config
中的<connectionManagement>
元素对其进行配置,但只有在您确实需要时才应该这样做。
基本上,通过不处理响应,您将连接池置于垃圾收集器的支配之下。
修复很简单:妥善处理资源:
using (var response = (HttpWebResponse)myReq.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
using (var reader = new XmlTextReader(responseStream))
{
// Whatever you need
}
}
}
请注意,我已删除了InputStreamReader
的创建 - 我在此处提供的代码更加强大,因为它将处理以不同编码返回的XML; XmlTextReader
会做正确的事。