日期:2014-05-19  浏览次数:20778 次

Thread的一个简单问题,有答案马上结帖
我在做一个数据采集的程序,当同时在多个网站采集数据时,如果有采集网站出现故障打不开或打开得非常慢时,就会导致异常使程序无法响应。

我的想法是当部分网站采集不了时,并不影响程序的运行,其他的采集任务还是能继续。

觉得只有用多线程处理,但之前没有应用过,所以请大家给个示例代码,谢谢!~

主要代码如下:

              //采集
                private   void   getInfo(string   url,Encoding   coding)
                {
                        //...
                        HttpWebRequest   request   =   (HttpWebRequest)WebRequest.Create(url);
                        request.Timeout   =   5000;
                        try
                        {

                                WebResponse   response   =   request.GetResponse();
                                Stream   strm   =   response.GetResponseStream();
                                StreamReader   sr   =   new   StreamReader(strm,   coding);
                                collectInfo   =   sr.ReadToEnd();
                                strm.Close();
                                sr.Close();
                        }
                        catch(Exception   ex)
                        {
                                MessageBox.Show(ex.Message);
                        }
                        //...
                }

//主程序里调用
                private   void   button1_Click(object   sender,   EventArgs   e)
                {
                        //...
                        CollectionInfo   coll   =   new   CollectionInfo();
                       
                        coll.getInfo( "http://www.site1.com/index.html ",Encoding.UTF8);
                       
                        coll.getInfo( "http://www.site2.com/index.aspx ",Encoding.UTF8);