StreamSocketListener ConnectionReceived和COMException

时间:2016-07-10 07:09:22

标签: c# thread-safety listener uwp comexception

我有一个听众,除了事件过于频繁的那一刻,它才能正常工作。在这种情况下,COMException"远程主机"强制关闭现有连接。它扔在线上

resp.FlushAsync() 

并且它没有被try-catch捕获。据我所知,这是因为进程是在单独的线程中进行的。

以下是简化示例:

 private readonly StreamSocketListener listener;

    // ... somewhere initialization
        this.listener = new StreamSocketListener();
        this.listener.ConnectionReceived += (s, e) => ProcessRequestAsync(e.Socket);
        this.listener.BindServiceNameAsync("8080");
    }

   // ... and event
    private async void ProcessRequestAsync(StreamSocket socket)
    {
        StringBuilder request = new StringBuilder();
        using (IInputStream input = socket.InputStream)
        {
            byte[] data = new byte[8192];
            IBuffer buffer = data.AsBuffer();
            uint dataRead = 8192;
            while (dataRead == 8192)
            {
                await input.ReadAsync(buffer, 8192, InputStreamOptions.Partial);
                request.Append(Encoding.UTF8.GetString(data, 0, data.Length));
                dataRead = buffer.Length;
            }
        }

        await Task.Delay(TimeSpan.FromSeconds(1));

        using (IOutputStream output = socket.OutputStream)
        {
            using (Stream resp = output.AsStreamForWrite())
            {
                byte[] headerArray = Encoding.UTF8.GetBytes("HTTP/1.1 404 Not Found\r\n" +
                                         "Content-Length:0\r\n" +
                                         "Connection: close\r\n\r\n");
                await resp.WriteAsync(headerArray, 0, headerArray.Length);

                await resp.FlushAsync();
            }
        }
    }

我试图做的事:
1.使用semaphoreSlim
2. catch(COMException)
3.添加this.listener.Control.KeepAlive = false; //或者也是如此 4.添加应用程序未处理的异常

有什么想法吗? ManualResetEvent的?

0 个答案:

没有答案