Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Error stop Http Listener

Error stop Http Listener

Scheduled Pinned Locked Moved C#
helpquestioncsharpsysadmintutorial
33 Posts 5 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • G Offline
    G Offline
    George_George
    wrote on last edited by
    #1

    Hello everyone, Here is my simple application code for a Windows Service application. The question is, when stop the service, there is always, // [System.InvalidOperationException] = {"Please call the Start() method before calling this method."} Does anyone have any ideas why there is such issue and how to fix?

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Diagnostics;
    using System.ServiceProcess;
    using System.Text;
    using System.Net;
    using System.Threading;

    namespace TestServiceStop1
    {
    public partial class Service1 : ServiceBase
    {
    private Thread _tHttpThread;
    private TestHttpServer _server;

        public Service1()
        {
            InitializeComponent();
        }
    
        protected override void OnStart(string\[\] args)
        {
            \_server = new TestHttpServer(this);
    
            \_tHttpThread = new Thread(\_server.StartListen);
    
            \_tHttpThread.Start();
        }
    
        protected override void OnStop()
        {
            // stop HTTP server
            \_server.Stop(false);
        }
    }
    
    public class TestHttpServer
    {
        // listening HTTP port
        private int \_Port = 0;
    
        // internal wrapped HTTP listener
        private HttpListener \_Server = new HttpListener();
    
        private Service1 \_manager;
    
        public TestHttpServer (Service1 manager)
        {
            \_manager = manager;
        }
    
        public int ListenPort
        {
            get
            {
                return \_Port;
            }
            set
            {
                \_Port = value;
            }
        }
    
        public void StartListen()
        {
            try
            {
                IAsyncResult result;
                \_Server.Prefixes.Add(String.Format("http://+:{0}/", 9099));
                \_Server.Start();
                while (true)
                {
                    result = \_Server.BeginGetContext(new AsyncCallback(this.HttpCallback), \_Server);
                    result.AsyncWaitHandle.WaitOne();
                }
            }
            // any exceptions are not expected
            // catch InvalidOperationException during service stop
            // \[System.InvalidOperationException\] = {"Please call the Start() method before calling this method."}
            catch (Exception ex)
            {
                throw ex;
            }
        }
    
    N G Z 3 Replies Last reply
    0
    • G George_George

      Hello everyone, Here is my simple application code for a Windows Service application. The question is, when stop the service, there is always, // [System.InvalidOperationException] = {"Please call the Start() method before calling this method."} Does anyone have any ideas why there is such issue and how to fix?

      using System;
      using System.Collections.Generic;
      using System.ComponentModel;
      using System.Data;
      using System.Diagnostics;
      using System.ServiceProcess;
      using System.Text;
      using System.Net;
      using System.Threading;

      namespace TestServiceStop1
      {
      public partial class Service1 : ServiceBase
      {
      private Thread _tHttpThread;
      private TestHttpServer _server;

          public Service1()
          {
              InitializeComponent();
          }
      
          protected override void OnStart(string\[\] args)
          {
              \_server = new TestHttpServer(this);
      
              \_tHttpThread = new Thread(\_server.StartListen);
      
              \_tHttpThread.Start();
          }
      
          protected override void OnStop()
          {
              // stop HTTP server
              \_server.Stop(false);
          }
      }
      
      public class TestHttpServer
      {
          // listening HTTP port
          private int \_Port = 0;
      
          // internal wrapped HTTP listener
          private HttpListener \_Server = new HttpListener();
      
          private Service1 \_manager;
      
          public TestHttpServer (Service1 manager)
          {
              \_manager = manager;
          }
      
          public int ListenPort
          {
              get
              {
                  return \_Port;
              }
              set
              {
                  \_Port = value;
              }
          }
      
          public void StartListen()
          {
              try
              {
                  IAsyncResult result;
                  \_Server.Prefixes.Add(String.Format("http://+:{0}/", 9099));
                  \_Server.Start();
                  while (true)
                  {
                      result = \_Server.BeginGetContext(new AsyncCallback(this.HttpCallback), \_Server);
                      result.AsyncWaitHandle.WaitOne();
                  }
              }
              // any exceptions are not expected
              // catch InvalidOperationException during service stop
              // \[System.InvalidOperationException\] = {"Please call the Start() method before calling this method."}
              catch (Exception ex)
              {
                  throw ex;
              }
          }
      
      N Offline
      N Offline
      N a v a n e e t h
      wrote on last edited by
      #2

      George_George wrote:

      _Server.Stop();

      I can't find where you are stopping the thread. You are just stopping the HTTPListener, not the thread. OnStop() method should be able to exit the thread also, I guess. Not sure this will be the reason for error.

      All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

      G 1 Reply Last reply
      0
      • G George_George

        Hello everyone, Here is my simple application code for a Windows Service application. The question is, when stop the service, there is always, // [System.InvalidOperationException] = {"Please call the Start() method before calling this method."} Does anyone have any ideas why there is such issue and how to fix?

        using System;
        using System.Collections.Generic;
        using System.ComponentModel;
        using System.Data;
        using System.Diagnostics;
        using System.ServiceProcess;
        using System.Text;
        using System.Net;
        using System.Threading;

        namespace TestServiceStop1
        {
        public partial class Service1 : ServiceBase
        {
        private Thread _tHttpThread;
        private TestHttpServer _server;

            public Service1()
            {
                InitializeComponent();
            }
        
            protected override void OnStart(string\[\] args)
            {
                \_server = new TestHttpServer(this);
        
                \_tHttpThread = new Thread(\_server.StartListen);
        
                \_tHttpThread.Start();
            }
        
            protected override void OnStop()
            {
                // stop HTTP server
                \_server.Stop(false);
            }
        }
        
        public class TestHttpServer
        {
            // listening HTTP port
            private int \_Port = 0;
        
            // internal wrapped HTTP listener
            private HttpListener \_Server = new HttpListener();
        
            private Service1 \_manager;
        
            public TestHttpServer (Service1 manager)
            {
                \_manager = manager;
            }
        
            public int ListenPort
            {
                get
                {
                    return \_Port;
                }
                set
                {
                    \_Port = value;
                }
            }
        
            public void StartListen()
            {
                try
                {
                    IAsyncResult result;
                    \_Server.Prefixes.Add(String.Format("http://+:{0}/", 9099));
                    \_Server.Start();
                    while (true)
                    {
                        result = \_Server.BeginGetContext(new AsyncCallback(this.HttpCallback), \_Server);
                        result.AsyncWaitHandle.WaitOne();
                    }
                }
                // any exceptions are not expected
                // catch InvalidOperationException during service stop
                // \[System.InvalidOperationException\] = {"Please call the Start() method before calling this method."}
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        
        G Offline
        G Offline
        GDavy
        wrote on last edited by
        #3

        George_George wrote:

        while (true) { result = _Server.BeginGetContext(new AsyncCallback(this.HttpCallback), _Server); result.AsyncWaitHandle.WaitOne(); }

        In your StartListen you get in this endless loop. So after stopping the server the call to

        _Server.BeginGetContext(new AsyncCallback(this.HttpCallback), _Server);

        most likely throws this exception. You will need to check if the _Server object is still active before calling the BeginGetContext I guess...

        G S 2 Replies Last reply
        0
        • G GDavy

          George_George wrote:

          while (true) { result = _Server.BeginGetContext(new AsyncCallback(this.HttpCallback), _Server); result.AsyncWaitHandle.WaitOne(); }

          In your StartListen you get in this endless loop. So after stopping the server the call to

          _Server.BeginGetContext(new AsyncCallback(this.HttpCallback), _Server);

          most likely throws this exception. You will need to check if the _Server object is still active before calling the BeginGetContext I guess...

          G Offline
          G Offline
          George_George
          wrote on last edited by
          #4

          Thanks GDavy, How do check whether _Server is still active? Any suggestions? :-) regards, George

          G 1 Reply Last reply
          0
          • N N a v a n e e t h

            George_George wrote:

            _Server.Stop();

            I can't find where you are stopping the thread. You are just stopping the HTTPListener, not the thread. OnStop() method should be able to exit the thread also, I guess. Not sure this will be the reason for error.

            All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

            G Offline
            G Offline
            George_George
            wrote on last edited by
            #5

            Sorry N a v a n e e t h, My English is not very good. You mean I need to stop the thread tHttpThread in OnStop? regards, George

            N 1 Reply Last reply
            0
            • G George_George

              Sorry N a v a n e e t h, My English is not very good. You mean I need to stop the thread tHttpThread in OnStop? regards, George

              N Offline
              N Offline
              N a v a n e e t h
              wrote on last edited by
              #6

              George_George wrote:

              You mean I need to stop the thread tHttpThread in OnStop?

              Yes. The thread is not stopping in your code. Stop that on OnStop() method.

              All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

              G G 2 Replies Last reply
              0
              • N N a v a n e e t h

                George_George wrote:

                You mean I need to stop the thread tHttpThread in OnStop?

                Yes. The thread is not stopping in your code. Stop that on OnStop() method.

                All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

                G Offline
                G Offline
                George_George
                wrote on last edited by
                #7

                Thanks N a v a n e e t h, How to stop the thread gracefully? I think of using Abort, but we have discussed before this method call is not a good idea always. regards, George

                N 1 Reply Last reply
                0
                • G George_George

                  Thanks GDavy, How do check whether _Server is still active? Any suggestions? :-) regards, George

                  G Offline
                  G Offline
                  GDavy
                  wrote on last edited by
                  #8

                  from MSDN on the BeginGetContext call[^] The InvalidOperationException is thrown when the server is stopped. So there you go it is normal behaviour. You can check the IsListening Property to see if the _Server is started or not.

                  G 1 Reply Last reply
                  0
                  • N N a v a n e e t h

                    George_George wrote:

                    You mean I need to stop the thread tHttpThread in OnStop?

                    Yes. The thread is not stopping in your code. Stop that on OnStop() method.

                    All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

                    G Offline
                    G Offline
                    GDavy
                    wrote on last edited by
                    #9

                    Actually because the BeginGetContext call will throw an exception when the _Server object is stopped, the thread will stop too so no extra work is actually required.

                    N 1 Reply Last reply
                    0
                    • G GDavy

                      Actually because the BeginGetContext call will throw an exception when the _Server object is stopped, the thread will stop too so no extra work is actually required.

                      N Offline
                      N Offline
                      N a v a n e e t h
                      wrote on last edited by
                      #10

                      I mean the thread which he created.

                      All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

                      G 1 Reply Last reply
                      0
                      • G George_George

                        Thanks N a v a n e e t h, How to stop the thread gracefully? I think of using Abort, but we have discussed before this method call is not a good idea always. regards, George

                        N Offline
                        N Offline
                        N a v a n e e t h
                        wrote on last edited by
                        #11

                        Go with this[^]. It will work.

                        All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

                        1 Reply Last reply
                        0
                        • N N a v a n e e t h

                          I mean the thread which he created.

                          All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

                          G Offline
                          G Offline
                          GDavy
                          wrote on last edited by
                          #12

                          ;) I know which thread you mean. The thread he creates uses the StartListening Function. In that function the BeginGetContext call is made, and this will throw the InvalidOperationException when the _Server object is stopped. So the thread he creates really does exit when the _Server stops. He will just need to catch the InvalidOperationException and evaluate that it is expected behaviour.

                          G N 2 Replies Last reply
                          0
                          • G GDavy

                            from MSDN on the BeginGetContext call[^] The InvalidOperationException is thrown when the server is stopped. So there you go it is normal behaviour. You can check the IsListening Property to see if the _Server is started or not.

                            G Offline
                            G Offline
                            George_George
                            wrote on last edited by
                            #13

                            Thanks GDavy, Your solution works. Cool! regards, George

                            1 Reply Last reply
                            0
                            • G GDavy

                              ;) I know which thread you mean. The thread he creates uses the StartListening Function. In that function the BeginGetContext call is made, and this will throw the InvalidOperationException when the _Server object is stopped. So the thread he creates really does exit when the _Server stops. He will just need to catch the InvalidOperationException and evaluate that it is expected behaviour.

                              G Offline
                              G Offline
                              George_George
                              wrote on last edited by
                              #14

                              Thanks GDavy! If I fixed in this way, are there any need to stop the tHttpThread thread?

                                          while (true)
                                          {
                                              if (\_Server.IsListening)
                                              {
                                                  result = \_Server.BeginGetContext(new AsyncCallback(this.HttpCallback), \_server);
                                                  result.AsyncWaitHandle.WaitOne();
                                              }
                                              else
                                              {
                                                  break;
                                              }
                                          }
                              

                              regards, George

                              1 Reply Last reply
                              0
                              • G GDavy

                                ;) I know which thread you mean. The thread he creates uses the StartListening Function. In that function the BeginGetContext call is made, and this will throw the InvalidOperationException when the _Server object is stopped. So the thread he creates really does exit when the _Server stops. He will just need to catch the InvalidOperationException and evaluate that it is expected behaviour.

                                N Offline
                                N Offline
                                N a v a n e e t h
                                wrote on last edited by
                                #15

                                GDavy wrote:

                                In that function the BeginGetContext call is made, and this will throw the InvalidOperationException when the _Server object is stopped. So the thread he creates really does exit when the _Server stops. He will just need to catch the InvalidOperationException

                                I know. I was suggesting him to stop that thread when HTTPListener stops, so it won't call again BeginGetContext(). Will that be a good method than catching exception, and thread getting aborted automatically ?

                                All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

                                G 1 Reply Last reply
                                0
                                • G George_George

                                  Hello everyone, Here is my simple application code for a Windows Service application. The question is, when stop the service, there is always, // [System.InvalidOperationException] = {"Please call the Start() method before calling this method."} Does anyone have any ideas why there is such issue and how to fix?

                                  using System;
                                  using System.Collections.Generic;
                                  using System.ComponentModel;
                                  using System.Data;
                                  using System.Diagnostics;
                                  using System.ServiceProcess;
                                  using System.Text;
                                  using System.Net;
                                  using System.Threading;

                                  namespace TestServiceStop1
                                  {
                                  public partial class Service1 : ServiceBase
                                  {
                                  private Thread _tHttpThread;
                                  private TestHttpServer _server;

                                      public Service1()
                                      {
                                          InitializeComponent();
                                      }
                                  
                                      protected override void OnStart(string\[\] args)
                                      {
                                          \_server = new TestHttpServer(this);
                                  
                                          \_tHttpThread = new Thread(\_server.StartListen);
                                  
                                          \_tHttpThread.Start();
                                      }
                                  
                                      protected override void OnStop()
                                      {
                                          // stop HTTP server
                                          \_server.Stop(false);
                                      }
                                  }
                                  
                                  public class TestHttpServer
                                  {
                                      // listening HTTP port
                                      private int \_Port = 0;
                                  
                                      // internal wrapped HTTP listener
                                      private HttpListener \_Server = new HttpListener();
                                  
                                      private Service1 \_manager;
                                  
                                      public TestHttpServer (Service1 manager)
                                      {
                                          \_manager = manager;
                                      }
                                  
                                      public int ListenPort
                                      {
                                          get
                                          {
                                              return \_Port;
                                          }
                                          set
                                          {
                                              \_Port = value;
                                          }
                                      }
                                  
                                      public void StartListen()
                                      {
                                          try
                                          {
                                              IAsyncResult result;
                                              \_Server.Prefixes.Add(String.Format("http://+:{0}/", 9099));
                                              \_Server.Start();
                                              while (true)
                                              {
                                                  result = \_Server.BeginGetContext(new AsyncCallback(this.HttpCallback), \_Server);
                                                  result.AsyncWaitHandle.WaitOne();
                                              }
                                          }
                                          // any exceptions are not expected
                                          // catch InvalidOperationException during service stop
                                          // \[System.InvalidOperationException\] = {"Please call the Start() method before calling this method."}
                                          catch (Exception ex)
                                          {
                                              throw ex;
                                          }
                                      }
                                  
                                  Z Offline
                                  Z Offline
                                  Zoltan Balazs
                                  wrote on last edited by
                                  #16

                                  George_George wrote:

                                  catch (Exception ex) { throw ex; }

                                  You're not doing anything with the exception and then you throw a modified exception (without the original stack trace). If you want to re-throw the original exception use

                                  throw;

                                  Simple.

                                  Work @ Network integrated solutions | Flickr | A practical use of the MVC pattern

                                  G 1 Reply Last reply
                                  0
                                  • Z Zoltan Balazs

                                    George_George wrote:

                                    catch (Exception ex) { throw ex; }

                                    You're not doing anything with the exception and then you throw a modified exception (without the original stack trace). If you want to re-throw the original exception use

                                    throw;

                                    Simple.

                                    Work @ Network integrated solutions | Flickr | A practical use of the MVC pattern

                                    G Offline
                                    G Offline
                                    George_George
                                    wrote on last edited by
                                    #17

                                    Thanks Zoltan, Good to learn from you. Any comments to? http://www.codeproject.com/script/Forums/View.aspx?fid=1649&msg=2580309[^] regards, George

                                    1 Reply Last reply
                                    0
                                    • N N a v a n e e t h

                                      GDavy wrote:

                                      In that function the BeginGetContext call is made, and this will throw the InvalidOperationException when the _Server object is stopped. So the thread he creates really does exit when the _Server stops. He will just need to catch the InvalidOperationException

                                      I know. I was suggesting him to stop that thread when HTTPListener stops, so it won't call again BeginGetContext(). Will that be a good method than catching exception, and thread getting aborted automatically ?

                                      All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

                                      G Offline
                                      G Offline
                                      George_George
                                      wrote on last edited by
                                      #18

                                      Thanks N a v a n e e t h, 1. Sounds good. Could you show the code please? I want to learn from you but feel do not know how to code. :-) 2. Any comments to? http://www.codeproject.com/script/Forums/View.aspx?fid=1649&msg=2580309[^] regards, George

                                      N 1 Reply Last reply
                                      0
                                      • G George_George

                                        Thanks N a v a n e e t h, 1. Sounds good. Could you show the code please? I want to learn from you but feel do not know how to code. :-) 2. Any comments to? http://www.codeproject.com/script/Forums/View.aspx?fid=1649&msg=2580309[^] regards, George

                                        N Offline
                                        N Offline
                                        N a v a n e e t h
                                        wrote on last edited by
                                        #19

                                        1 -

                                        volatile bool continue = true;
                                        public void StartListen()
                                        {
                                        try
                                        {
                                        IAsyncResult result;
                                        _Server.Prefixes.Add(String.Format("http://+:{0}/", 9099));
                                        _Server.Start();
                                        while (continue)
                                        {
                                        result = _Server.BeginGetContext(new AsyncCallback(this.HttpCallback), _Server);
                                        result.AsyncWaitHandle.WaitOne();
                                        }
                                        }
                                        // any exceptions are not expected
                                        // catch InvalidOperationException during service stop
                                        // [System.InvalidOperationException] = {"Please call the Start() method before calling this method."}
                                        catch (Exception ex)
                                        {
                                        throw ex;
                                        }
                                        }

                                            public void Stop(bool isTerminate)
                                            {
                                                **continue = false;**
                                                \_Server.Stop();
                                            }
                                        

                                        2 - It looks fine.

                                        All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

                                        G 1 Reply Last reply
                                        0
                                        • N N a v a n e e t h

                                          1 -

                                          volatile bool continue = true;
                                          public void StartListen()
                                          {
                                          try
                                          {
                                          IAsyncResult result;
                                          _Server.Prefixes.Add(String.Format("http://+:{0}/", 9099));
                                          _Server.Start();
                                          while (continue)
                                          {
                                          result = _Server.BeginGetContext(new AsyncCallback(this.HttpCallback), _Server);
                                          result.AsyncWaitHandle.WaitOne();
                                          }
                                          }
                                          // any exceptions are not expected
                                          // catch InvalidOperationException during service stop
                                          // [System.InvalidOperationException] = {"Please call the Start() method before calling this method."}
                                          catch (Exception ex)
                                          {
                                          throw ex;
                                          }
                                          }

                                              public void Stop(bool isTerminate)
                                              {
                                                  **continue = false;**
                                                  \_Server.Stop();
                                              }
                                          

                                          2 - It looks fine.

                                          All C# applications should call Application.Quit(); in the beginning to avoid any .NET problems.- Unclyclopedia How to use google | Ask smart questions

                                          G Offline
                                          G Offline
                                          George_George
                                          wrote on last edited by
                                          #20

                                          Thanks N a v a n e e t h, I think your code has an issue when we are executing result = _Server.BeginGetContext(new AsyncCallback(this.HttpCallback), _Server) while at the same time, Stop is called. :-) In this situation, there is no chance to check continue status variable. Any comments? regards, George

                                          N 2 Replies Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups