0

I have IDisposable Business class : private o_Entities context;

    public o_Entities GetContext()
    {
        if (context == null)
            context = new o_Entities();

        return context;
    }


 public List<SModel> List(int s_id)
        {
            var currentContext = GetContext();
            var s = (from c in currentContext.tS
                         where (s_id == 0 || s_id == null || (c.s_id == s_id))
                         orderby c.s_id ascending
                         select new SModel
                         {
                             s_id = c.s_id,
                             s_name = c.s_name,
                             address = c.address,
                             phone = c.phone.Trim()
                         });

            return s.ToList();
}

private bool disposed = false;

    protected virtual void Dispose(bool disposing)
    {
        if (!this.disposed)
        {
            if (disposing)
            {
                context.Dispose();
            }
        }
        this.disposed = true;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

I have put break point on Dispose() function but it is never called. is there anything wrong?

Thank You.

Mina A-va
  • 3
  • 2

1 Answers1

0

Dispose() is not called automatically (it is not like a destructor in C++). You are responsible for calling it when you no longer need the object.

See this question for more information.

Community
  • 1
  • 1
Robert Hegner
  • 9,014
  • 7
  • 62
  • 98
  • But I have used SuppressFinalize () method. as I understood - when finalize is used - dispose will be called automatically. Am I wrong? – Mina A-va Aug 18 '15 at 12:25
  • No, `Disposed()` is never called automatically by the Garbage Collector. You can have a finalizer in your class which is called by the Garbage Collector, and from there you can call `Dispose(false)`. Please have a look at the link in my answer. You can find an example there. – Robert Hegner Aug 18 '15 at 12:35
  • thank you, Robert. Bu again, there is written : Implementing IDisposable provides a way for users of your class to release resources early, instead of waiting for the garbage collector. and in the end of my class i have **protected virtual void Dispose(bool disposing)** so it must be released, right? – Mina A-va Aug 18 '15 at 13:01
  • Yes, but you also need to call that `protected virtual void Dispose(bool disposing)` method somewhere. If you want to have it called when your object is garbage collected, then you can call it from the finalizer of your class. If the name of your class is `MyClass` then your finalizer would look like this: `~MyClass() { Dispose(false); }`. Again, please look at the link in my answer. The first answer there contains a complete code example. The last line in that example is the finanlizer with a call to `Dispose()`. – Robert Hegner Aug 18 '15 at 13:12