62,074
社区成员
发帖
与我相关
我的任务
分享
public class PageTool
{
/// <summary>
/// 请求地址
/// </summary>
public string Url { get; set; }
/// <summary>
/// 超时时间(毫秒)
/// </summary>
public int TimeOut { get; set; }
/// <summary>
/// 页面内容
/// </summary>
public string PageHtml { get; set; }
public void GetPage()
{
WebResponse response1 = null;
Stream stream1 = null;
StreamReader sr = null;
try
{
WebRequest request1 = WebRequest.Create(Url);
request1.ContentType = "application/x-www-form-urlencoded";
request1.Timeout = TimeOut;
response1 = request1.GetResponse();
stream1 = response1.GetResponseStream();
sr = new StreamReader(stream1, System.Text.Encoding.UTF8);
PageHtml = sr.ReadToEnd();
}
catch (Exception exception2)
{
// 记录日志
}
finally
{
if (sr != null)
sr.Close();
if (stream1 != null)
stream1.Close();
if (response1 != null)
response1.Close();
}
}
}
......
public void GetPages()
{
Thread th = null;
try
{
PageTool tool = new PageTool();
tool.Url = "https://forum.csdn.net/PointForum/Forum/PostTopic.aspx";
tool.TimeOut = 6000;
th = new Thread(new ThreadStart(tool.GetPage));
th.Start();
}
catch(Exception ex)
{
// 记录日志
}
finally
{
if(th!=null)
th.Abort();
// 如果是主线程先完成,子线程没完成,终止子线程时红色位置会报错
// System.Threading.ThreadAbortException: 正在中止线程。
// 在 System.Net.ConnectStream.Read(Byte[] buffer, Int32 offset, Int32 size)
// 在 System.IO.StreamReader.ReadBuffer()
// 在 System.IO.StreamReader.ReadToEnd()
}
}
......