62,041
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
/// 根据相传入的数据,得到相应页面数据,并对数据进行处理
/// </summary>
/// <param name="item">参数类对象</param>
/// <returns>返回HttpResult类型</returns>
public void GetAsyncHtml(Item item, Action<string> action)
{
SetItem(item);
HttpInformation information = new HttpInformation();
{
information.Action = action;
information.Request = request;
}
IAsyncResult result = request.BeginGetResponse(new AsyncCallback(EndGetAsyncHtml), information);
}
public void EndGetAsyncHtml(IAsyncResult result)
{
HttpInformation information = (HttpInformation)result.AsyncState;
HttpWebRequest request = information.Request;
Action<string> action = information.Action;
response = (HttpWebResponse)request.EndGetResponse(result);
//获取服务器返回的资源
using (response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default))
{
string html = reader.ReadToEnd();
action(html);
}
}
}
listBox1.Items.Clear();
sw.Restart();
HTMLHelper helper = new HTMLHelper();
for (int i = 0; i < num; i++)
{
helper.GetAsyncHtml(new Item() { Url = "http://localhost:3333/hehe.aspx" }, d => AddList(d));
}
Thread th = new Thread(new ParameterizedThreadStart(ShowHtml));
th.IsBackground = true;
th.Start(num);
这是用线程池实现的
private void ThreadGet_Click(object sender, EventArgs e)
{
sw.Restart();
listBox1.Items.Clear();
List<Task> list = new List<Task>();
for (int i = 0; i < num; i++)
{
Task temp = Task.Factory.StartNew(AddHtml);
list.Add(temp);
}
Task.WaitAll(list.ToArray());
sw.Stop();
MessageBox.Show(sw.Elapsed.ToString());
}
public void AddHtml()
{
HTMLHelper helper = new HTMLHelper();
helper.GetHtml(new Item() { Url = "http://localhost:3333/hehe.aspx"});
}
public string GetHtml(Item item)
{
string html = string.Empty;
SetItem(item);
//获取服务器返回的资源
using (response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default))
{
html = reader.ReadToEnd();
}
}
if(request!=null)
{
request.Abort();
}
return html;
}
protected void Page_Load(object sender, EventArgs e)
{
//跟这个粒度有关
Thread.Sleep(100);
}