首页 新闻 会员 周边

HttpListener关闭抛异常问题

0
[已解决问题] 解决于 2022-06-30 17:29
问题:http关闭后,task估计还在运行,断点打不到,
异常信息:System.Net.HttpListenerException (0x80004005): 由于线程退出或应用
程序请求,已中止 I/O 操作。在 System.Net.HttpListener.GetContext()
代码:
方法调用
  static void Main(string[]args){
      HttpServer.Start();
      Thread.Sleep(2000);
      HttpServer.Stop();
      Console.ReadKey();
}
public class HttpServer{
    private static HttpListener httpListener;
    private static CancellationTokenSource cancelToken;
    public static void Start(){
     httpListener = new HttpListener();
            httpListener.Prefixes.Add("http://+:8048/");
            httpListener.Start();
            cancelToken = new CancellationTokenSource();
            Task.Run(() => { handlehttp(); }, cancelToken.Token);
    }


    public static void Stop(){
       httpListener.Stop();
       httpListener.Close();
       cancelToken.Cancel();
    }
    private void handlehttp(){
      while(true){
       try{
         if (cancelToken.IsCancellationRequested)
         {
          break;
         }
         if(!httpListener.IsListening){break;}
        var context = httpListener.GetContext();//结束这句一直报错
       }catch(Exception ex){
       }
     }
    }

}
< >
分享
最佳答案
0

public static void Stop(){ 这里赋值 httpListener=null
handlehttp 检查httpListener空的话直接返回应该就行了吧

奖励园豆:5
2012 | 高人七级 |园豆:21230 | 2020-12-04 08:36

过不了哈,httpListener.GetContext()这个引发的,没有再次出现循环,昨天试了net core 的 task,也有问题,线程没有停止,使用thread的话,没有实现abort方法,net 5 也是报上面的错,3.1好像不会报错,但task线程不会停止

apgk | 园豆:47 (初学一级) | 2020-12-04 08:38

@apgk: httpListener如果已经无效了,httpListener.GetContext()这个肯定出问题的

如果是并发的话,Stop和handlehttp需要处理下同步,一定要控制销毁httpListener后不能在handlehttp对它进行操作了

2012 | 园豆:21230 (高人七级) | 2020-12-04 08:48

@2012: handlehttp本身没有任何操作,只是等待接入而已,但目前就是getcontext()先抛出异常,这里一直等待监听的,其实是想看下httpListener 停止后,getcontext()为啥出个异常,net4.5 使用thread ,那么 getcontext()捕捉 threadabortexception 就没有 httplistenerexception错误,真的很神奇的一幕。

apgk | 园豆:47 (初学一级) | 2020-12-04 08:52

@apgk: stop工作在另一个线程,handlehttp工作在一个线程。 stop中httpListener.Close将httpListener这个资源销毁了,httpListener.getcontext调用自然是有问题的

net4.5 使用thread,此时触发了threadabortexception,而这个异常的层次 https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.threadabortexception?redirectedfrom=MSDN&view=net-5.0
集成于Exception,相当于catch到了,这样程序就相当于忽略了这个异常

2012 | 园豆:21230 (高人七级) | 2020-12-04 08:59

@2012: 你试试就知道了,使用thread 不会抛出httplistenerexception 这个异常,thread abort肯定会触发threadabortexception,我知道的,上面代码net 都会跑错,net core 不会(线程应该没结束),net core 未实现 thread abort,所以线程无法停止,你试试就知道了。

apgk | 园豆:47 (初学一级) | 2020-12-04 09:03
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册