我试图通过在HttpWebRequest上设置Range标头来获取部分URI,然后使用Begin / EndGetResponse异步请求它们:
using System;
using System.Net;
namespace MultiGet
{
class Program
{
static void GetterCallback(IAsyncResult ip)
{
try
{
var req = (HttpWebRequest)ip.AsyncState;
var response = req.EndGetResponse(ip);
Console.WriteLine("In GetterCallback {0}",req.Headers["Range"]);
response.Close();
}
catch
{
Console.WriteLine("Exception Thrown");
}
}
static void Main(string[] args)
{
string URI = "http://www.microsoft.com";
var req = (HttpWebRequest)WebRequest.Create(URI);
req.Method = WebRequestMethods.Http.Head;
var response = req.GetResponse();
int TotalSize = Int32.Parse(response.Headers["Content-Length"]);
Console.WriteLine("URI Content-Length {0}",TotalSize);
Console.WriteLine("Now requesting the URI in 10 parts");
Int32 start = 0;
var splitreq = new HttpWebRequest[10];
var results = new IAsyncResult[10];
for (int i = 0; i < 10; i++)
{
Int32 end = start + TotalSize / 10 - 1;
if (i == 9) end = TotalSize;
splitreq[i] = (HttpWebRequest)WebRequest.Create(URI);
splitreq[i].AddRange(start, end);
results[i] = splitreq[i].BeginGetResponse(new AsyncCallback(GetterCallback), splitreq[i]);
start = end + 1;
}
Console.ReadKey(true);
//This shows that some async calls did not complete
foreach (var result in results)
{
Console.WriteLine(result.IsCompleted);
}
}
}
}
即使我等了很长时间(没有按下Console.ReadKey(true)),所有请求都没有完成。我不确定我哪里出错了。
答案 0 :(得分:1)
一个可能的问题是您没有对响应使用using
语句,因此它们可能会保留池中的HTTP连接。
例如,我建议您将回调更改为:
static void GetterCallback(IAsyncResult ip)
{
try
{
var req = (HttpWebRequest)ip.AsyncState;
using (var response = req.EndGetResponse(ip))
{
Console.WriteLine("In GetterCallback {0}",req.Headers["Range"]);
}
}
catch
{
Console.WriteLine("Exception Thrown");
}
}
在您的计划的早期,当您找到内容长度时:
int TotalSize;
using (var response = (HttpWebResponse) req.GetResponse())
{
TotalSize = (int)response.ContentLength;
}
当你做出这些改变后,再试一次......它肯定对我有用。