none
HttpClient 多线程 异常无法捕获; RRS feed

  • 问题

  •     class HttpClientClass
        {
            //public ManualResetEvent allDone = new ManualResetEvent(false);
            public CookieContainer cc = null;
            public Encoding encoding = Encoding.GetEncoding("utf-8");//默认utf-8
            public string accept = "text/html, application/xhtml+xml, */*";
            public string referer = null;
            public string accept_language = "en-US";//zh-CN
            public string user_agent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";
            public string content_type = "application/x-www-form-urlencoded";
            public string accept_encoding = "gzip, deflate";
            public string connection = "Keep-Alive";
            public int timeout = 10000;
            private ExceptionClass exceptionClass = new ExceptionClass();
            public string getHtml(string url, CookieContainer cc)
            {
                try
                {
                    HttpClient client = null;
                    HttpClientHandler handler = null;
                    HttpResponseMessage response = null;
                    HttpContent httpContent = null;
                    try
                    {
                        handler = new HttpClientHandler()
                        {
                            CookieContainer = cc,
                            UseCookies = true,
                            AllowAutoRedirect = true,
                        };
                        // ... Use HttpClient.            
                        client = new HttpClient();
    
                        #region 添加head
                        client.DefaultRequestHeaders.Add("Accept", accept);
                        if (referer != null)
                        {
                            client.DefaultRequestHeaders.Add("Referer", referer);
                        }
                        client.DefaultRequestHeaders.Add("Accept-Language", accept_language);
                        client.DefaultRequestHeaders.Add("User-Agent", user_agent);
                        //client.DefaultRequestHeaders.Add("Connection", connection);
                        //client.DefaultRequestHeaders.Add("Content-type", content_type);
                        //client.DefaultRequestHeaders.Add("Accept-Encoding",accept_encoding);
                        #endregion
    
                        client.Timeout = new TimeSpan(timeout * 10000);
                        //var byteArray = Encoding.ASCII.GetBytes("username:password1234");
                        //client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
                        MessageBox.Show("1");
                        response = client.GetAsync(url).Result;//运行这句代码程序抛出AggregateException异常,并且捕获不到;
                        MessageBox.Show("2");
                        httpContent = response.Content;
    
                        // ... Check Status Code                                
                        //Console.WriteLine("Response StatusCode: " + (int)response.StatusCode);//输出状态码;
    
                        // ... Read the string.
                        string result = httpContent.ReadAsStringAsync().Result;
                        // ... Display the result.
                        return result;//有可能返回null;
                    }
                    catch (AggregateException ae)//超时引发的异常
                    {
    
                        Console.WriteLine("threadroc:AggregateException");
                        return null;
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(exceptionClass.getExceptionMsg("HttpClientClass", e));
                        return null;
                    }
                    finally
                    {
                        if (client != null)
                        {
                            client.Dispose();
                        }
                        if (handler != null)
                        {
                            handler.Dispose();
                        }
                        if (response != null)
                        {
                            response.Dispose();
                        }
                        if (httpContent != null)
                        {
                            httpContent.Dispose();
                        }
                    }
                }
                catch
                {
                    MessageBox.Show("");
                    return null;
                }
            }
        }
    

    代码就是这样了,然后用了100个委托代理相当于100个线程把,实例化了100个类,每个线程实例化一个类,在这类做http访问,但是1~3个线程完全能正常运行,异常也能捕获到,我如果开100线程的话,直接抛异常而且还是捕获不到的那种,另外说明一下,我虽然开了100线程,但是锁住了,也就是说我执行这方法的时候,只有一个线程在执行,其他线程全等待着,

    类似这样

    lock(静态对象)

    {

    new HttpClientClass.getHtml(url,new CookieContainer);

    }

    其他线程根本不会调用这方法的,让我纳闷的是,线程一多,直接就抛异常,还捕获不到,这算是微软框架的bug么......

    最后先行谢谢各位大大的解答

    2014年3月22日 10:48

答案

  • //创建200个委托代理,并把方法传进去.
                    for (int i = 0; i < RocVariableClass.threadAmount; i++)
                    {
                        //delegateFun dgc = new delegateFun(startThread);
                        ////listdgc.Add(dgc);//把委托代理添加到集合?
                        //IAsyncResult ir = dgc.BeginInvoke(dgcCallBack, dgc);//启动委托,异步可以用此
                        Thread threadClass = new Thread(()=>startThread());
                        threadClass.IsBackground = true;
                        threadClass.Start();
                        RocVariableClass.threadCount++;//线程数+1;
                        if (labelThreadCount != null)
                        {
                            setLabelThreadCountText();
                        }
                    }

    问题解决了,用HttpClient不能用委托代替线程启动,只能用线程启动,谢谢各位大大的帮助.虽然一个也没恢复我的  - -

    • 已标记为答案 Roc Thread 2014年3月22日 12:34
    2014年3月22日 12:34

全部回复

  • //创建200个委托代理,并把方法传进去.
                    for (int i = 0; i < RocVariableClass.threadAmount; i++)
                    {
                        //delegateFun dgc = new delegateFun(startThread);
                        ////listdgc.Add(dgc);//把委托代理添加到集合?
                        //IAsyncResult ir = dgc.BeginInvoke(dgcCallBack, dgc);//启动委托,异步可以用此
                        Thread threadClass = new Thread(()=>startThread());
                        threadClass.IsBackground = true;
                        threadClass.Start();
                        RocVariableClass.threadCount++;//线程数+1;
                        if (labelThreadCount != null)
                        {
                            setLabelThreadCountText();
                        }
                    }

    问题解决了,用HttpClient不能用委托代替线程启动,只能用线程启动,谢谢各位大大的帮助.虽然一个也没恢复我的  - -

    • 已标记为答案 Roc Thread 2014年3月22日 12:34
    2014年3月22日 12:34
  • 感谢分享经验。


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    2014年3月24日 11:38
    版主