首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WebClient DownloadString()计数器?

WebClient DownloadString()计数器?
EN

Stack Overflow用户
提问于 2015-05-18 23:57:40
回答 1查看 214关注 0票数 2
代码语言:javascript
复制
 WebClient client = new WebClient();
 string url = "https://someurl.com/..."
 string get = client.DownloadString(url);

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

EN

回答 1

Stack Overflow用户

发布于 2016-06-19 04:51:21

解决这个问题的一种方法是将WebClient子类化并覆盖您想要获取统计数据的方法。我在下面的实现中选择了保留通过GetWebRequest的任何url的统计信息。我对代码进行了广泛的注释,所以我认为很明显,它可以归结为在字典中保留每个Uri的计数。

代码语言:javascript
复制
// 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);
        }
    }
}

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

代码语言:javascript
复制
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次

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30307822

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档