【发布时间】:2015-11-05 16:43:25
【问题描述】:
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 中协同工作。
但它不起作用..这个问题是因为线程?
每个班级都不一样..
【问题讨论】:
-
顺便说一句,现在是了解 .NET 命名约定并开始应用它们的好时机。
-
另外,请阅读
CancellationToken- 比使用 volatile bool 更简洁的解决方案 - 您的应用在请求停止后可能需要 5 秒才能关闭。 -
你在哪里设置 RequestStop() ?!!我的意思是 _shouldStop = true;
标签: c# multithreading api asyncsocket