CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 19
  1. #1
    George2 is offline Elite Member Power Poster
    Join Date
    Oct 2002
    Posts
    4,468

    Error stop Http Listener

    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?

    Code:
    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;
                }
            }
    
            public void Stop(bool isTerminate)
            {
                _Server.Stop();
            }
    
            // callback function when there is HTTP request received
            private void HttpCallback(IAsyncResult result)
            {
                HttpListenerContext context = _Server.EndGetContext(result);
                HandleRequest(context);
            }
    
            // find matched URL HTTP request handler and invoke related handler
            private void HandleRequest(HttpListenerContext context)
            {
                string matchUrl = context.Request.Url.AbsolutePath.Trim().ToLower();
    
                context.Response.StatusCode = 200;
                context.Response.StatusDescription = "OK";
                context.Response.Close();
            }
        } // end of Http Listener class
    }

    thanks in advance,
    George

  2. #2
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Error stop Http Listener

    Assuming your thread has started and called:
    Code:
    _Server.Start();
    Check to see if it's listening before calling Stop
    Code:
    public void Stop(bool isTerminate)
    {
      if( _Server.IsListening )
      {
        _Server.Stop();
      }  
    }

  3. #3
    Join Date
    Oct 2003
    Location
    .NET2.0 / VS2005 Developer
    Posts
    7,104

    Re: Error stop Http Listener

    Er.. Just a bit of curiousity about your Async code.. I dont think it actually works asyncronously.. If you get a handle to the result and then wait on it, that's syncronous code.. So why did you bother with all the async code?
    "it's a fax from your dog, Mr Dansworth. It looks like your cat" - Gary Larson...DW1: Data Walkthroughs 1.1...DW2: Data Walkthroughs 2.0...DDS: The DataSet Designer Surface...ANO: ADO.NET2 Orientation...DAN: Deeper ADO.NET...DNU...PQ

  4. #4
    George2 is offline Elite Member Power Poster
    Join Date
    Oct 2002
    Posts
    4,468

    Re: Error stop Http Listener

    Thanks Arjay,


    It works. I do not know why adding the block will fix this issue. Any more descriptions please? :-)

    Quote Originally Posted by Arjay
    Assuming your thread has started and called:
    Code:
    _Server.Start();
    Check to see if it's listening before calling Stop
    Code:
    public void Stop(bool isTerminate)
    {
      if( _Server.IsListening )
      {
        _Server.Stop();
      }  
    }

    regards,
    George

  5. #5
    George2 is offline Elite Member Power Poster
    Join Date
    Oct 2002
    Posts
    4,468

    Re: Error stop Http Listener

    Thanks cjard,


    I have tested that it is listening in a synchronous way but handle in an asycnrhonous way -- means multiple threads could be in method HandleRequest.

    If you think there are any issues which causes my code not working in an asynchronous way, could you provide more description please?

    Quote Originally Posted by cjard
    Er.. Just a bit of curiousity about your Async code.. I dont think it actually works asyncronously.. If you get a handle to the result and then wait on it, that's syncronous code.. So why did you bother with all the async code?

    regards,
    George

  6. #6
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Error stop Http Listener

    Quote Originally Posted by George2
    Thanks Arjay,


    It works. I do not know why adding the block will fix this issue. Any more descriptions please? :-)




    regards,
    George
    It's really quite simple. The developers that wrote the Stop method don't want you to call Stop unless the listener is in the listening state. Are you sure that Start is getting called?

  7. #7
    George2 is offline Elite Member Power Poster
    Join Date
    Oct 2002
    Posts
    4,468

    Re: Error stop Http Listener

    Hi Arjay,


    1.

    I am sure Start is called by debugging. Please correct me if I am wrong.

    2.

    I think your code does not fix the root cause, it just prevent the Stop on HttpListener from being called. And you rely on the process/service termination to stop the HttpListener thread.

    Any comments?

    Quote Originally Posted by Arjay
    It's really quite simple. The developers that wrote the Stop method don't want you to call Stop unless the listener is in the listening state. Are you sure that Start is getting called?

    regards,
    George

  8. #8
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Error stop Http Listener

    Quote Originally Posted by George2
    I think your code does not fix the root cause
    George, don't blame my suggestion - I didn't write the HttpListener code.

    Use reflector to compare the HttpListener Stop( ) with SqlConnection Close(). You'll notice that internally, SqlConnection checks if a connection has been Opened before closing it. I don't have any idea why HttpListener wouldn't internally do this check.

    As far as a concern about HttpListener threads, in .Net any background threads will get closed when the object goes out of scope.

  9. #9
    Join Date
    Mar 2002
    Location
    St. Petersburg, Florida, USA
    Posts
    12,125

    Re: Error stop Http Listener

    The difference is largely a philosphical one but does have some basis on the overall pattern including pooling.

    HttpListeners (and many other classes) are designed to (generally) work in a paradigm where they are opened at specific locations and closed at a location that is equivilant in the structure.

    SQLConnections are NOT designed to be used this way. They should ONLY be opened right before a command is executed, and should be closed after all information is transfered.

    In most implementations this means that the Open and Close will be at radically different latyers of the program. Adding the requirement that the developer is responsible for coodinating this would greatly complicate things.

    By implementing it the way it is, you can Close() a connection without knowing if the code actually opened it.

    Code:
    void A(SqlConnection conn) { B(conn); }
    void B(SqlConnection conn) { C(conn); }
    void C(SqlConnection conn) { D(conn); }
    void E(SqlConnection conn) { E(conn); }
    void F(SqlConnection conn) { F( if (something) conn.Open()); }
    
    void TestCode()
    {
    SqlConnection conn = new SqlConnection(....);
    A(conn);
    conn.Close();
    }
    
    or even better....
    void TestCode()
    {
       using (SqlConnection conn = new SqlConnection(....))
      {
           A(conn);
       }
    }
    Make sense???
    TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
    2008, 2009,2010
    In theory, there is no difference between theory and practice; in practice there is.

    * Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions
    * How NOT to post a question here
    * Of course you read this carefully before you posted
    * Need homework help? Read this first

  10. #10
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Error stop Http Listener

    Perhaps the usage between the two classes are slightly different; however, nothing is gained by forcing the developer to make the check prior to calling the Close method.

    Consider if in a newer version the HttpListener class was changed internally make the check in the Close method, would there be any downside? Any code that made an explicit IsListening check would still work. Any newer code could just call Close() without the explicit IsListening check.

    Btw, if I recall correctly in the .Net 1.0 timeframe, users of the SqlConnection classes used to have to explicitly check the connection state prior to calling Close().

    Code:
    SqlConnection connection = new SqlConnection( ... );
    
    try 
    {
        connection.Open();
    
       // do something with the connection
    }
    finally
    {
      if( connection.State == ConnectionState.Open )
      {
        connection.Close();
      }
    }
    This was before the IDisposable interface and the using block was in .Net. I would guess that it made sense to internalize the connection state check at that time because it wouldn't have really helped much to still have to check the state and close it inside a using block.

    // Fortunately today we don't have to write code like this
    Code:
    using( SqlConnection connection = new SqlConnection( ... ) )
    {
      try 
      {
          connection.Open();
    
         // do something with the connection
      }
      finally
      {
        if( connection.State == ConnectionState.Open )
        {
          connection.Close();
        }
      }
    }
    Last edited by Arjay; June 3rd, 2008 at 09:30 PM.

  11. #11
    Join Date
    Mar 2002
    Location
    St. Petersburg, Florida, USA
    Posts
    12,125

    Re: Error stop Http Listener

    IDisposable interface was completely available in .Net 1.1

    http://msdn.microsoft.com/en-us/libr...m.idisposable(VS.71).aspx

    Granted that in DAO and (non- .NET) ADO, the situation was different, but that comparision is really stretching things....

    Granted that there would be no problem "per-se" with having the check [ie it would not "break" things], but given that I have NEVER written an application using HttpListener where the Open and Close statements were not paired in the same class, it has never ben an issue, AND there have been at least two occasions where that type of error (Closing something I thought should be Open) revealed subtle but serious bugs that might have otherwise leaked into production.....
    TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
    2008, 2009,2010
    In theory, there is no difference between theory and practice; in practice there is.

    * Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions
    * How NOT to post a question here
    * Of course you read this carefully before you posted
    * Need homework help? Read this first

  12. #12
    Join Date
    Jan 2006
    Location
    Fox Lake, IL
    Posts
    15,007

    Re: Error stop Http Listener

    And I tried mixing one connection string for two different tables and had nothing but trouble. Finally just used the same one over and over.
    David

    CodeGuru Article: Bound Controls are Evil-VB6
    2013 Samples: MS CODE Samples

    CodeGuru Reviewer
    2006 Dell CSP
    2006, 2007 & 2008 MVP Visual Basic
    If your question has been answered satisfactorily, and it has been helpful, then, please, Rate this Post!

  13. #13
    George2 is offline Elite Member Power Poster
    Join Date
    Oct 2002
    Posts
    4,468

    Re: Error stop Http Listener

    Hi TheCPUWizard,


    I think you mean in below quoted statements there is no need to check open status before call close for SQLConnection, but for HttpListener, we need to check for whether it is started before calling Close, right?

    (sorry my English is not good, and I need your confirmation on this key point)

    Quote Originally Posted by TheCPUWizard
    The difference is largely a philosphical one but does have some basis on the overall pattern including pooling.

    HttpListeners (and many other classes) are designed to (generally) work in a paradigm where they are opened at specific locations and closed at a location that is equivilant in the structure.

    SQLConnections are NOT designed to be used this way. They should ONLY be opened right before a command is executed, and should be closed after all information is transfered.

    regards,
    George

  14. #14
    George2 is offline Elite Member Power Poster
    Join Date
    Oct 2002
    Posts
    4,468

    Re: Error stop Http Listener

    Hi TheCPUWizard,


    The link is broken, could you post the correct link please? :-)

    Quote Originally Posted by TheCPUWizard
    IDisposable interface was completely available in .Net 1.1

    http://msdn.microsoft.com/en-us/libr...m.idisposable(VS.71).aspx

    Granted that in DAO and (non- .NET) ADO, the situation was different, but that comparision is really stretching things....

    Granted that there would be no problem "per-se" with having the check [ie it would not "break" things], but given that I have NEVER written an application using HttpListener where the Open and Close statements were not paired in the same class, it has never ben an issue, AND there have been at least two occasions where that type of error (Closing something I thought should be Open) revealed subtle but serious bugs that might have otherwise leaked into production.....

    regards,
    George

  15. #15
    George2 is offline Elite Member Power Poster
    Join Date
    Oct 2002
    Posts
    4,468

    Re: Error stop Http Listener

    Hi dglienna,


    I am confused about what do you mean -- "mixing one connection string for two different tables"? Do you mean SQL Server connection string? It contains only server name and database name. No table name.

    Anyway, could you show me the code please, about how to "ixing one connection string for two different tables and had nothing but trouble"?

    Quote Originally Posted by dglienna
    And I tried mixing one connection string for two different tables and had nothing but trouble. Finally just used the same one over and over.

    regards,
    George

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured