Search code examples
c#asp.netstack-overflowdispose

StackOverflowException when disposing an object


I have created a class to store search values to a session. Such that when I get back to the search page from another page, I can get the values stored in the session. When the search page loads, I'm getting the values from the session, fill up the text fields and dispose the object afterwards. But I get a StackOverflowException when I try to dispose the object. Why does this happen and how do I fix it?

    public class SearchValue : IDisposable{
          public int ID {get; set;}
          public string Name {get; set;}

          public void Dispose()
          {
              this.Dispose();
          }
     }

            public void SaveSearchValueToSession()
            {
                SearchValue searchValue = new SearchValue();
                searchValue.ID = Convert.ToInt32(txtID.Text);
                searchValue.Name = txtName.Text;
                Session["SEARCH_VALUE"] = searchValue;
            }

protected void Page_Load(object sender, EventArgs e){
      SearchValue searchValue = (SearchValue)Session["SEARCH_VALUE"];
      txtID.Text = searchValue.ID.ToString();
      txtName.Text = searchValue.Name;

      //Right here I would like to dispose the object
      searchValue.Dispose()
}

Solution

  • You are calling the same method from inside the Dispose method. This will indeed cause a StackOverflowException. I do wonder if you really need to implement IDisposable and if you understand its purpose...

    If you really need to:

    1. Give a meaningful implementation of Dispose, free unmanaged resources, etc;
    2. Use using around the variable;
    3. Don't save it inside the Session after disposal.

    Also read the Fundamentals of Garbage Collection.

    From comments I notice you are worried of creating too much objects. Don't worry, it is no problem here. This is especially true since your object (single) doesn't get garbage collected now: you save it in the session where it will live until the session is distroyed. You keep reusing the very same object over and over again.