HttpListener关闭抛异常问题
问题: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){ } } } }
回答
public static void Stop(){ 这里赋值 httpListener=null
handlehttp 检查httpListener空的话直接返回应该就行了吧