Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在异常发生后修复httplistener_C#_Asynchronous_Exception_Httplistener - Fatal编程技术网

C# 如何在异常发生后修复httplistener

C# 如何在异常发生后修复httplistener,c#,asynchronous,exception,httplistener,C#,Asynchronous,Exception,Httplistener,我有一个HttpListener,它接收多个请求,问题是每次发生异常时,侦听器都停止工作,我尝试停止并重新启动服务器,但它仍然卡在GetContextAsync中。 我不熟悉异步编程 public class HttpServer{ public HttpServer(string id) { try { _id= id; var prefix = $"http://localhost:39633/queries/{id

我有一个HttpListener,它接收多个请求,问题是每次发生异常时,侦听器都停止工作,我尝试停止并重新启动服务器,但它仍然卡在GetContextAsync中。 我不熟悉异步编程

public class HttpServer{

 public HttpServer(string id)
    {
        try {
            _id= id;
            var prefix = $"http://localhost:39633/queries/{id}/";
            _listener = new HttpListener();
           _listener.Start();

        }
        catch (Exception e) {

        }
    }

    public async Task Start()
    {
        try {
            while(true ) {
                var context = await _listener.GetContextAsync().ConfigureAwait(false);// it stays here
                HandleRequest(context); // handle incoming requests
            }
        }
        catch (Exception e) {

        }
    }
}
我希望服务器继续运行,有没有办法做到这一点

您的捕获块在您的循环之外。因此,每次发生异常时,它都会离开循环。因此,您只需反转while并重试,这样您就可以在循环中检查异常,并决定是否要重试或中止

public async Task Start() {
    while(true) {
        try {
            var context = await _listener.GetContextAsync().ConfigureAwait(false);// it stays here
            HandleRequest(context); // handle incoming requests
        } catch (HttpListenerException e) {
            // examine e.ErrorCode to see what the problem was and
            // decide to continue or return
        } catch (Exception e) {
            // decide to continue or return
        }
    }
}
与GetContextAsync的工作原理相同的表示,当它抛出HttpListenerException时,这意味着:

Win32函数调用失败。检查异常的属性以确定异常的原因

根据我的经验,只有当你故意阻止听者时,才会抛出这个词。但也许出了什么问题。如果您在异常中告诉我们消息,我们可能会提供更多帮助


如果它对您有帮助,我确实写了一篇文章,其中有关于的示例代码。

非常感谢您的快速回复,我有一个excel应用程序,可以从外部源加载数据,当数据太大时,用户可以取消操作,异常显示System.Net.HttpListenerException:“在不存在的网络连接上尝试了一个操作。然后,是的,您应该进行我描述的更改并查找它。该特定错误应该有一个特定的错误代码,您可以对其进行不同的处理。调用Stop还将抛出HttpListenerException,因此您不想忽略该异常。错误代码是1229,我不知道该怎么办:如果您想继续循环的下一次迭代,您真的不需要做任何事情。除非你想记录任何你认为应该停止循环的错误,然后你返回。这正是我正在做的。。但是http侦听器不再接收任何请求,除非我再次调用start,否则它将停止。即使我这样做了,它也会被困在阅读中: