委托多线程EndInvoke

本文关键字:EndInvoke 多线程 | 更新日期: 2023-09-27 18:24:17

我的.aspx文件中的此方法。。。

   private static string GetPageAsString(string address)
        {
            AsyncWebRequester.StartRequest(address);
            TimeSpan timeout = new TimeSpan(1000000);  // 1 second=10,000,000          
            DateTime tryToGetAnswerUntil = DateTime.Now.Add(timeout);
            string returnXML = "";
            while (string.IsNullOrEmpty(returnXML) && DateTime.Now < tryToGetAnswerUntil )
            {
                returnXML = AsyncWebRequester.GetResult(address);                
            }
            return returnXML;
        }

访问此类中的方法。。。

public class AsyncWebRequester
    {
        private static Dictionary<string, string> retrievedxml = new Dictionary<string, string>();
        public static void StartRequest(string uri)
        {
            try
            {
                InitiateAsyncRequestDelegate mydelegate = new InitiateAsyncRequestDelegate(InitiateAsyncRequest);
                mydelegate.BeginInvoke(uri, null, null);
            }
            catch {}
        }      
        private delegate void InitiateAsyncRequestDelegate(string uri); 
        private static void InitiateAsyncRequest(string uri) 
        {
            WebRequest request;
            try
            {
                request = WebRequest.Create(uri);              
                using (WebResponse response = request.GetResponse())
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream());
                    string result = reader.ReadToEnd();
                    retrievedxml.Add(uri, result);
                }
            }
            catch { }
            finally { request = null; }
        }
        public static string GetResult(string uri)
        {
            string xml = "";
            if (retrievedxml.ContainsKey(uri))
            {            
                xml = retrievedxml[uri];
                retrievedxml.Remove(uri);
            }
            return xml;              
        }
    } 

基本上这意味着:即发即弃一些线程从网站上请求xml。如果我从网站上得到xml,那就好了;否则我就忘了线程。无论如何,实际上,我只是忘记了线程(据我所知)。

问题是:这可以吗,或者我应该做点什么来主动终止线程(EndInvoke()?),或者GarbageCollector帮我处理它,这样我就不会冒着耗尽内存或以其他方式让服务器屈服的风险。换句话说:我的代码是防弹的吗?

委托多线程EndInvoke

您确实需要调用EndInvoke()

在您的情况下,您应该只调用ThreadPool.QueueUserWorkItem;它更简单。