Async

A simple delegate for simultaneous execution of a given method

/// <summary>
        /// Executes the requests asynchronous.
        /// </summary>
        /// <param name="workToProcess">The work to process.</param>
        /// <returns></returns>
        public static string[] ExecuteRequestsAsynchronous(String[] workToProcess)
        {
            // Some local variables
            string[] results = new string[workToProcess.Length];
            int numToDo = workToProcess.Length;
            AutoResetEvent done = new AutoResetEvent(false);

            Dictionary<string, string> hashResults = new Dictionary<string, string>(workToProcess.Length);

            // Main execution
            for (int i = 0; i < workToProcess.Length; i++)
            {
                ThreadPool.QueueUserWorkItem
                (
                    delegate(Object obj)
                    {
                        string query = (string)obj;
                        hashResults[query] = ExecuteRequest(query);

                        // Release main thread by setting done                    
                        if (Interlocked.Decrement(ref numToDo) == 0)
                        {
                            done.Set();
                        }
                    }, workToProcess[i]
                );
            }

            // wait for all threads
            done.WaitOne();

            // Show the results
            for (Int32 i = 0; i < workToProcess.Length; i++)
            {
                results[i] = hashResults[workToProcess[i]];
            }

            return results;
        }

A simple web request for a web page

/// <summary>
        /// Executes the request.
        /// </summary>
        /// <param name="query">The query.</param>
                /// <returns></returns>
        public static String ExecuteRequest(String query)
        {
            if (string.IsNullOrEmpty(query)) { throw new ArgumentException("Url cannot be null or empty", "query"); }
            WebRequest        request;
            WebResponse        response;
            Stream            receiveStream;
            StreamReader    receiveStreamReader;

            Encoding        encode        = Encoding.GetEncoding("utf-8");
            String            pageHtml    = String.Empty;

            try
            {
                request                = WebRequest.Create(query);
                request.Timeout        = 30000;
                response            = request.GetResponse();

                Trace.WriteLine(string.Format("{0},{1},{2} ",request.RequestUri, response.ResponseUri, (request.RequestUri == response.ResponseUri)));

                using (receiveStream = response.GetResponseStream())
                {
                    using (receiveStreamReader = new StreamReader(receiveStream, encode))
                    {
                        pageHtml = receiveStreamReader.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(string.Format("{0},{1},{2} ",query, string.Empty, "False" ));
                Console.WriteLine(string.Format("Error getting: {0}", query), ex.Message);
            }

            return pageHtml;
        }
    }

Simple delegate wire up

private void InvokeService()
{
    HelloWorldService service = new HelloWorldService();

    service.HelloWorldCompleted += new HelloWorldCompletedEventHandler(this.HelloWorldCompleted);
    service.HelloWorldAsync();
}

Simple delegate Handler

private void HelloWorldCompleted(object sender,
                         HelloWorldCompletedEventArgs args)
{
    Console.WriteLine(args.Result);
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License