WebClient DownloadString() counter?

本文关键字:counter DownloadString WebClient | 更新日期: 2023-09-27 17:49:32

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

我如何计算url被下载了多少次?

WebClient DownloadString() counter?

解决这个问题的一种方法是子类化WebClient并覆盖您想要进行统计的方法。我在下面的实现中选择了保存通过GetWebRequest的任何url的统计信息。我已经对代码进行了广泛的注释,所以我认为很明显它可以归结为在字典中保持每个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次
https://stackexchange.com/被使用了1次
https://meta.stackexchange.com/被使用了1次
http://example.com/被使用了1次

我认为复数错误是理所当然的