我如何检查HttpListenerRequest连接是否仍然打开?

时间:2017-06-02 20:40:57

标签: c# console-application

我想检查连接是否仍然打开。如果不是,我会停止这个过程。

         //Process request code goes here

         while (!isComplete) {
            //Check HttpListenerRequest if connection is still open...

            if (IsTimedOut && !timeoutTriggered)
            {
                timeoutTriggered = triggerTimeout();
            }

            Thread.Sleep(100);
        }
        stopWatch.Stop();
        //Process response code goes here

我该怎么做?

1 个答案:

答案 0 :(得分:0)

我用写/刷对解决了这个问题。 连接关闭后,Flush会抛出异常。

try
{
    //Checks whether the connection is still open
    var encoding = Encoding.Default;
    byte[] utf8Bytes = Encoding.Convert(encoding, Encoding.UTF8, encoding.GetBytes(" "));
    listenerContext.Response.OutputStream.Write(utf8Bytes, 0, utf8Bytes.Length);
    listenerContext.Response.OutputStream.Flush();
}
catch (Exception e)
{
    Console.WriteLine(e);
    eventStream.TriggerEvent(new ActionEventArgs(this, ActionEventStreamer.SYSTEM_CANCEL));
    break;
}