委托多线程EndInvoke?

时间:2012-02-10 18:37:32

标签: c# asp.net multithreading asynchronous delegates

我的.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是否为我处理它,所以我不冒险将内存匮乏或将服务器带到它的位置膝盖以其他方式。换句话说:我的代码是防弹吗?

1 个答案:

答案 0 :(得分:1)

您需要致电EndInvoke()

在您的情况下,您应该拨打ThreadPool.QueueUserWorkItem;它更简单。