我已经实现了一个简单的方法,它会定期轮询服务以获取公共 IP 地址。
Stopwatch sw = new Stopwatch();
while (true)
{
Console.WriteLine("(HttpWebRequest)WebRequest.Create...");
sw.Restart();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://checkip.dyndns.org/");
sw.Stop();
Console.WriteLine("HttpWebRequest was created in {0} ms", sw.ElapsedMilliseconds);
request.Proxy = null;
sw.Restart();
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
sw.Stop();
Console.WriteLine("Response was received in {0} ms", sw.ElapsedMilliseconds);
StreamReader sr = new StreamReader(response.GetResponseStream());
string responseStr = sr.ReadToEnd().Trim();
string ipStr = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")).Matches(responseStr)[0].ToString();
IPAddress address = IPAddress.Parse(ipStr);
Console.WriteLine("IP: {0}", address.ToString());
}
Console.WriteLine();
Thread.Sleep(60000);
}
该方法第一次WebRequest.Create
创建该方法需要将近 10 秒,而在随后的调用中,几乎会立即创建相同的实例。HttpWebRequest
这种行为的原因是什么?
更新。这是我从 Visual Studio 启动可执行文件(发布模式)时的输出。
(HttpWebRequest)WebRequest.Create...
HttpWebRequest was created in 9758 ms
Response was received in 683 ms
(HttpWebRequest)WebRequest.Create...
HttpWebRequest was created in 0 ms
Response was received in 617 ms
(HttpWebRequest)WebRequest.Create...
HttpWebRequest was created in 0 ms
Response was received in 1034 ms
(HttpWebRequest)WebRequest.Create...
HttpWebRequest was created in 0 ms
Response was received in 641 ms
(HttpWebRequest)WebRequest.Create...
HttpWebRequest was created in 0 ms
Response was received in 652 ms
(HttpWebRequest)WebRequest.Create...
HttpWebRequest was created in 0 ms
Response was received in 672 ms
(HttpWebRequest)WebRequest.Create...
HttpWebRequest was created in 0 ms
Response was received in 658 ms
(HttpWebRequest)WebRequest.Create...
HttpWebRequest was created in 0 ms
Response was received in 655 ms
(HttpWebRequest)WebRequest.Create...
HttpWebRequest was created in 0 ms
Response was received in 1067 ms
(HttpWebRequest)WebRequest.Create...
HttpWebRequest was created in 0 ms
Response was received in 651 ms
(HttpWebRequest)WebRequest.Create...
HttpWebRequest was created in 0 ms
Response was received in 643 ms
编辑:
我在具有 2 GB RAM、Intel Core 2 Duo T7500、下载连接速度为 7 Mbps 和上传速度为 640 Kbps 的计算机上使用 Windows 7 SP1 32 位。