locked
Will never returning from an event handler cause a StackOverflowException? RRS feed

  • Question

  • User314655009 posted

    Hello,

    My Web app does not return from an EventHandler.  Does this cause a StackOverflowException?

    The reason is to maintain a Reverse-Ajax Comet control connection for dynamic updates of a text editor web control from an AsyncPostBack.

    Here is my code:

           protected void EnterButton_Click(object sender, EventArgs e)
            {
                bool bHandleEvent = true;
    
                //never leave event handler
                while (true)
                {
                    Run(bHandleEvent);
    
                    Thread.Sleep(500);
    
                    bHandleEvent = false;
                }
            }

    The Run method contains the actual EventHandler code.  (Which includes client calls via the Comet control.)

    Again, will a StackOverflowException occur after a lengthy session?

    Any suggestions on a solution?

    williamj

    Thursday, November 10, 2016 7:55 PM

All replies

  • User283571144 posted

    Hi williamj7,

    The Run method contains the actual EventHandler code.  (Which includes client calls via the Comet control.)

    Again, will a StackOverflowException occur after a lengthy session?

    Any suggestions on a solution?

    As far as I know, StackOverflowException is thrown when the execution stack overflows because it contains too many nested method calls.

    So if you bHandleEvent doesn't call Run(bHandleEvent) method again, it will not throw the StackOverflowException.

    Here is a little sample which will throw the StackOverflowException.

        static int ctr = 0;
    
       public static void Main()
       {
          Example ex = new Example();
          ex.Execute();
          Console.WriteLine("\nThe call counter: {0}", ctr);
       }
    
       private void Execute()
       {
          ctr++;
          if (ctr % 50 == 0)
             Console.WriteLine("Call number {0} to the Execute method", ctr);
    
             Execute();
    
          ctr--;
       }

    You could see the "Execute" method nested "Execute“ method and it is always executed.

    So this will show the StackOverflowException.

    Best Regards,

    Brando

    Friday, November 11, 2016 6:28 AM