当前位置: 首页 > 编程语言 > C#

干净地中断HttpListener的BeginGetContext方法分享

时间:2023-04-10 21:27:44 C#

干净地中断HttpListener的BeginGetContext方法我正在使用HttpListener并使用BeginGetContext来获取我的上下文对象。我想干净地关闭我的HttpListener,但是如果我尝试对侦听器执行Close,我会得到一个异常,导致我的程序退出。使用系统;使用System.Net;namespaceSandbox_Console{classProgram{publicstaticvoidMain(){if(!HttpListener.IsSupported){Console.WriteLine("WindowsXPSP2或Server2003需要使用HttpListener类。");返回;}//创建一个监听器。HttpListener监听器=newHttpListener();listener.Prefixes.Add("http://vwdev.vw.local:8081/BitsTest/");监听器.Start();Console.WriteLine("正在收听...");listener.BeginGetContext(上下文,侦听器);控制台.ReadLine();听众.Close();//此行出现异常,但未显示在VisualStudioConsole.WriteLine("StoppedListening...");//这条线永远不会到达。控制台.ReadLine();}staticvoidContext(IAsyncResultresult){HttpListenerlistener=(HttpListener)result.AsyncState;HttpListenerContextcontext=listener.EndGetContext(result);context.Response.Close();listener.BeginGetContext(上下文,侦听器);}}}该程序在listener.Close()上引发异常,但错误永远不会在VisualStudio中显示,我我得到的唯一注释是调试输出屏幕中的以下内容:System.dll程序“[2568]SandboxConsole.vshost.exe:Managed(v4.0.30319)”中发生类型为“System.ObjectDisposedException”的第一次机会异常已退出使用代码0(0x0)我能够从Windows事件查看器获取真正执行的应用程序:SandboxConsole.exe框架版本:v4.0.30319描述:进程因未处理的异常而终止。异常信息:System.ObjectDisposedException堆:在System.Net.HttpListener.EndGetContext(System.IAsyncResult)在Sandbox_Console.Program.Context(System.IAsyncResult)在System.Net.LazyAsyncResult.Complete(IntPtr)在System.Net.ListenerAsyncResult。WaitCallback(UInt32,UInt32,System.Threading.NativeOverlapped*)inSystem.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32,UInt32,System.Threading.NativeOverlapped*)我需要做什么才能彻底关闭HttpListener?当你调用Close时,上次调用Context时,你必须处理可能抛出的对象disposeexceptionstaticvoidContext(IAsyncResultresult){HttpListenerlistener=(HttpListener)result.AsyncState;try{//如果我们没有监听,这一行将抛出ObjectDisposedException。HttpListenerContextcontext=listener.EndGetContext(result);context.Response.Close();listener.BeginGetContext(上下文,侦听器);}catch(ObjectDisposedException){//故意不对异常做任何事情。你可以在上面添加这一行是C#学习教程:干净地中断HttpList如果ener的BeginGetContext方法分享的所有内容对你有用,需要进一步了解C#学习教程,希望你多多关注——if(!listener.IsListening){return;}HttpListenerContextcontext=listener.EndGetContext(ctx);本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如有转载请注明出处: