Question: I am trying to enhance the performance of writing thousands of rows to a db using EF. I have found that the speed of SaveChanges() degrades over time within a single context, and disposing and recreating the context after n inserts can help this.

```
using(Context context = new Context())
{
    for(int i = 0; i < numberOfLines; i++)
    {
        context.Collection.AddObject(line);
        if (i % 100 == 0)
        {
            context.SaveChanges()
            // Here I would like to call dispose on context and then create a new one
        }
     }
}

```

Of course, I need to use using or do something similar because there is a lot more going on and I need to ensure that dispose will be called if an exception gets thrown at any time.

Any ideas? I know I can declare the context outside of a try block, and then have a finally with context.Dispose(). I obviously don't want to do that though.

EDIT: I realized the code snippet I posted doesn't totally show why I am trying to do this. The for loop calls context.SaveChanges() in other spots outside of the IF statement. So when the IF evaluates to true, I've called SaveChanges() a number of times already.

Answer: 
Because identifiers inside of a `using` are read only, you can't just set it to a new object. I'd say the best option is to do exactly what you said you don't want to do and use a `try/finally` instead of a using:

```
Context context = null;
try
{
    context = new Context();

    for (int i = 0; i < numberOfLines; i++)
    {
        context.Collection.AddObject(line);
        if (i % 100 == 0)
        {
            context.SaveChanges();
            context.Dispose();
            context = new Context();
        }
    }
}
finally { context.Dispose(); }

```

While you could technically do what you want by creating a new disposable object that wraps another disposable object and allows that wrapped object to be mutated, it would be a poor practice. C# *specifically* goes out of its way to make the given identifier read-only because it is particularly confusing for that object to be changing during the `using` block, and it makes the code much harder to reason about, but if you really want to do it, you can:

```
using (var context = new EvilMutableDisposableWrapper<Context>(new Context()))
{
    for (int i = 0; i < numberOfLines; i++)
    {
        context.Wrapped.Collection.AddObject(line);
        if (i % 100 == 0)
        {
            context.Wrapped.SaveChanges();
            context.Dispose();
            context.Wrapped = new Context();
        }
    }
}

```

Please don't do this though.
How's this:

```
const int ChunkSize = 100;
for(int i = 0; i < numberOfLines; i += ChunkSize)
{
    using(Context context = new Context())
    {
        for(int j = i; j < i + ChunkSize && j < numberOfLines; j++)
        {
            // if needed, use j within this loop, not i
            context.Collection.AddObject(line);
        }
        context.SaveChanges()
     }
}

```