-1

i am improving speed and resource usage of an huge HIS application that have more than 200 winForms and they use entityContext like these :

private void someMethod()
{
    var context = new entityContext();
    var qry = context.someTable.Where(x=>x.condition);//bring thousands of records
    ...
    ... do some thing with result

    ...
    //EOF method. here is problem :
    /*
     * is context will be free all the records that brings to ram 
     * in the end of method without using  context.Dispose()?
     * i think NO!
     */
}

is there any way to find all of the entityContext object that created in the form and dispose them?

if i use at winForms Closed event this.Dispose(true); is it enough to dispose all of them?

public class myForm : System.Windows.Forms.Form
{
    protected override void OnClosed(EventArgs e)
    {
        base.OnClosed(e);

        /*
         * TODO: 
         *      find all entityContext objects and dispose them
         */ 

        this.Dispose(true);
    }
}

i don't have time to edit all codes to wrap all entityContextobjects in a using{} clause or add manually context.Dispose() to them or etc ...

i am looking for a way to dispose all of them in the OnClosed() event is these possible?

patachi
  • 315
  • 1
  • 2
  • 18
  • 1
    It is not clear why you lost track of them and need to find them back. Or for that matter why you'd wait until the user closes the window. – Hans Passant Aug 23 '13 at 11:52

1 Answers1

0

The recommended way is to wrap all your context objects in a using{} clause. This way they will be automatically disposed when exiting the using. Also the norm is to use short lived context objects.

Searching with reflection for all instances of DbContext (or any Type for that matter) is not possible in .NET (at least not easily) as far as I know. And reflection, even if this is possible, will hurt your performance.

Having context objects as singletons in repositories (if this pattern has been used) can also help you towards disposing them especially if your repos are implementing IDisposable.

idipous
  • 2,868
  • 3
  • 30
  • 45
  • i just have one week that 1 day is passed and i don't want to spend all week on adding using{} to context objects or change code to use Singleton and test it – patachi Aug 23 '13 at 12:09
  • 1
    As I said in my answer you cannot do this automatically with reflection. – idipous Aug 23 '13 at 13:02