C#get和Thread类只工作两次,我不知道确切

use*_*846 0 c# api multithreading asyncsocket

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);
Run Code Online (Sandbox Code Playgroud)

这个程序只工作两次getWeather().

我不知道为什么这个程序只运行两次..

我创建了asyncsocket服务器并在Main Function中一起工作.

但它不起作用..这个问题是因为线程?

每个班级都不同..

Jon*_*eet 5

我不知道为什么这个程序只运行两次..

因为默认HTTP连接池的大小为每个主机2个连接 - 并且您正在使用它们.您可以使用<connectionManagement>元素配置它app.config,但是只有在您真正需要时才应该这样做.

基本上,通过不处理响应,您将使连接池受到垃圾收集器的支配.

修复很简单:适当地处理资源:

using (var response = (HttpWebResponse)myReq.GetResponse())
{
    using (var responseStream = response.GetResponseStream())
    {
        using (var reader = new XmlTextReader(responseStream))
        {
            // Whatever you need
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,我已经删除了InputStreamReader- 我在这里介绍的代码更加健壮,因为它将处理以不同编码返回的XML; XmlTextReader会做正确的事.