Cleanly interrupt HttpListener's BeginGetContext method

烈酒焚心 提交于 2019-12-05 03:29:15

Context gets called one last time when you call Close, you must handle the object disposed exception that could get thrown

static void Context(IAsyncResult result)
{
    HttpListener listener = (HttpListener)result.AsyncState;

   try
   {
        //If we are not listening this line throws a ObjectDisposedException.
        HttpListenerContext context = listener.EndGetContext(result);

        context.Response.Close();
        listener.BeginGetContext(Context, listener);
   }
   catch (ObjectDisposedException)
   {
       //Intentionally not doing anything with the exception.
   }
}

You could add this line

if (!listener.IsListening) { return; }
HttpListenerContext context = listener.EndGetContext(ctx);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!