如何添加其他方法?

时间:2015-10-28 19:20:44

标签: c# http

我有两个类,我想在MyWebRequest类中添加一个方法。在这种方法中,我必须计算我正在进行的HTTP请求。 请帮我解决一下这个。 Program.cs

using System;
using System.Collections.Generic;
using System.IO;

namespace HTTP
{
    class Program
    {
        static void Main(string[] args)
        {
            var lstWebSites = new List<string>
            {
                "www.amazon.com",
                "www.ebay.com",
                "www.att.com",
                "www.verizon.com",
                "www.sprint.com",
                "www.centurylink.com",
                "www.yahoo.com"
            };
            string filename = "RequestLog.csv";
            {
                using (var writer = new StreamWriter(filename, true))
                {
                    foreach (string website in lstWebSites)
                    {
                        for (var i = 0; i < 4; i++)
                        {
                            MyWebRequest request = new MyWebRequest();
                            request.Request();
                        }
                    }
                }
            }
        }
    }
}

这是MyWebRequest.cs,这是我想要完成所有http请求以及检索响应所需时间的地方。

using System;
using System.IO;
using System.Net;

namespace HTTP
{
    class MyWebRequest
    {
        public void Request()
        {
            HttpWebResponse response = null;

            try
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("lstWebSites");
                request.Method = "GET";

                response = (HttpWebResponse)request.GetResponse();

                using (StreamReader sr = new StreamReader(response.GetResponseStream()));
            }
            catch (WebException e)
            {
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    response = (HttpWebResponse)e.Response;
                    Console.Write("Errorcode: {0}", (int)response.StatusCode);
                }
                else
                {
                    Console.WriteLine("Error: {0}", e.Status);
                }
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:4)

秒表怎么样?

using System.Diagnostics;

Stopwatch stopwatch = new Stopwatch();
using (var writer = new StreamWriter(filename, true))
{
    foreach (string website in lstWebSites)
    {
        for (var i = 0; i < 4; i++)
        {

            MyWebRequest request = new MyWebRequest();
            stopwatch.Start();
            request.Request();
            stopwatch.Stop();
            Console.WriteLine("Time elapse: {0}", stopwatch.Elapse);
            stopwatch.Restart();
        }
    }
}