System.Threading.ThreadAbortException: 正在中止线程

mimangshamo mimangshamo 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
现在遇到一个问题,问题的大概描述就是,我在子线程中执行抓页面的操作,但是主线程处理完后就会终止这个子线程,但是子线程这时候如果没完成,那么就会出现如题的异常,代码如下:

报错的行:PageHtml = sr.ReadToEnd();

用于子线程调用的对象(由于我需要传值和取返回值,所以就定义一个实体类)

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()
}
}
......
...全文

相关推荐

评论 2
收藏 已收藏
分享
返回顶部
mimangshamo
.NET社区 62,274 成员 668,968 内容