C# WebClient DownloadString()计数器?
如何计算C# WebClient DownloadString()计数器?,c#,C#,如何计算url已下载多少次?解决此问题的一种方法是对WebClient进行子类化,并覆盖要获取统计信息的方法。在下面的实现中,我选择保存通过GetWebRequest的任何url的统计信息。我已经对代码进行了大量的注释,因此我认为很明显,它可以归结为在字典中保留每个Uri的计数 WebClient client = new WebClient(); string url = "https://someurl.com/..." string get = client.DownloadStri
url
已下载多少次?解决此问题的一种方法是对WebClient
进行子类化,并覆盖要获取统计信息的方法。在下面的实现中,我选择保存通过GetWebRequest
的任何url的统计信息。我已经对代码进行了大量的注释,因此我认为很明显,它可以归结为在字典中保留每个Uri
的计数
WebClient client = new WebClient();
string url = "https://someurl.com/..."
string get = client.DownloadString(url);
这将输出:
使用3次使用1次
使用1次
使用1次
使用1次
我认为这是理所当然的。一个接一个地数<代码>下载_计数器+=1代码>由您的代码下载?或者任何人下载?只需使用一个普通变量,解释更多内容即可help@freedomn-我是通过代码下载的。
// 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);
}