gpt4 book ai didi

c# - WebClient DownloadString() 计数器?

转载 作者:太空宇宙 更新时间:2023-11-03 13:07:24 25 4
gpt4 key购买 nike

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

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

最佳答案

解决此问题的一种方法是子类化 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/ is used 3 times
https://meta.stackoverflow.com/ is used 1 times
https://stackexchange.com/ is used 1 times
https://meta.stackexchange.com/ is used 1 times
http://example.com/ is used 1 times

我会选择 pluralization bug理所当然。

关于c# - WebClient DownloadString() 计数器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30307822/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com