WebClient DownloadString()计数器?

时间:2015-05-18 15:57:40

标签: c#

 WebClient client = new WebClient();
 string url = "https://someurl.com/..."
 string get = client.DownloadString(url);

如何计算已下载url的次数?

1 个答案:

答案 0 :(得分:1)

解决此问题的一种方法是继承WebClient并覆盖要对其进行统计的方法。我已在以下实施中选择保留通过GetWebRequest的任何网址的统计信息。我已经对代码进行了广泛的评论,因此我认为很清楚它可以归结为在字典中保持每Uri的计数。

// subclass WebClient
public class WebClientWithStats:WebClient
{
    // appdomain wide storage
    static Dictionary<Uri, long> stats = new Dictionary<Uri, long>();

    protected override WebResponse GetWebResponse(WebRequest request)
    {
        // prevent multiple threads changing shared state
        lock(stats)
        {
            long count;
            // do we have thr Uri already, if yes, gets its current count
            if (stats.TryGetValue(request.RequestUri, out count))
            {
                // add one and update value in dictionary
                count++;
                stats[request.RequestUri] = count;
            }
            else
            {
                // create a new entry with value 1 in the dictionary
                stats.Add(request.RequestUri, 1);
            }
        }
        return base.GetWebResponse(request);
    }

    // make statistics available 
    public static Dictionary<Uri, long> Statistics
    {
        get
        {
            return new Dictionary<Uri, long>(stats);
        }
    }
}

典型的使用场景如下所示:

using(var wc = new WebClientWithStats())
{
    wc.DownloadString("http://stackoverflow.com");
    wc.DownloadString("http://stackoverflow.com");
    wc.DownloadString("http://stackoverflow.com");
    wc.DownloadString("http://meta.stackoverflow.com");
    wc.DownloadString("http://stackexchange.com");
    wc.DownloadString("http://meta.stackexchange.com");
    wc.DownloadString("http://example.com");
}

var results = WebClientWithStats.Statistics;
foreach (var res in results)
{
    Console.WriteLine("{0} is used {1} times", res.Key, res.Value);
}

将输出:

  

https://stackoverflow.com/使用3次   https://meta.stackoverflow.com/使用1次   http://stackexchange.com/使用1次   https://meta.stackexchange.com/使用1次   http://example.com/使用了1次

我认为pluralization bug是理所当然的。