Is Disposing of Entity Framework context object required - c#

We are using entity framework for communication with database in our WCF service methods, recently we run the code review tool on our service code. As usual we got many review proposals by tool and many review comments were suggesting to dispose the Entity Framework context object. So, my question is if I use a Entity Framework context object within a method and once I come out of the method, GC doesn't clean up the context object ? do we need to explicitly dispose context object ?

Simply: DbContext implements IDisposable, therefore you should dispose of it, manually, as soon as you're done with it.
You don't need to dispose of it, because the GC will collect it eventually, but the GC isn't deterministic: you never know when "eventually" will be. Until it's disposed, it will be holding resources that aren't in use - for example, it may still have an open database connection. Those resources aren't freed until the GC runs, unless you dispose manually. Depending on specific details you may find that you have unnecessarily blocked network resources, file accesses, and you will certainly be keeping more memory reserved than you need to.
There's a further potential hit, too: when you dispose of an object manually, the GC doesn't typically need to call the Finalizer on that object (if there is one). If you leave the GC to automatically dispose of an object with a Finalizer, it'll place the object in a Finalizer Queue - and will automatically promote the object to the next GC generation. This means that an object with a finalizer will always hang around for orders of magnitude longer than it needs to before being GCed (as successive GC generations are collected less frequently). DBContext would likely fall into this category as the underlying database connection will be unmanaged code.
(Useful reference.)

I think the best approach is coding it within a using statement
using(var cx = new DbContext())
{
//your stuff here
}
so it got automaitaclly disposed

In general if something implements IDisposable it's a Good Idea(TM) to explicitly dispose of it when you're through. This is especially true if you do not own the implementation of said object; you should treat it as a black box in this case. Additionally, even if it were not necessarily "required" to dispose of it now, it may be in the future.
Therefore, IMHO the question of whether you "need to" explicitly dispose of the object is irrelevant. If it is asking to be disposed of - by virtue of implementing IDisposable - it should be disposed of.

The recommended thing to do with a DBContext is to not dispose of it at all (it is the exception to the rule in most cases), even though is a disposable object.
An example of the issue, ths first example is taking a call and evaluation it in the using statement, while the second evaluates it after. (first ons runs, second one throws error The operation cannot be completed because the DbContext has been disposed.)
List<Test> listT;
using (Model1 db = new Model1())
{
listT = db.Tests.ToList(); //ToList Evaluates
}
foreach (var a in listT)
{
Console.WriteLine(a.value);
}
IEnumerable<Test> listT1;
using (Model1 db = new Model1())
{
listT1 = db.Tests;
}
foreach (var a in listT1) //foreach evaluates (but at wrong time)
{
Console.WriteLine(a.value);
}
The same issue happens in
IEnumerable<Test> listT1;
Model1 db = new Model1();
listT1 = db.Tests;
db.Dispose();
foreach (var a in listT1) //foreach evaluates (but at wrong time)
{
Console.WriteLine(a.value);
}
Aslong as you dont open the connection manually you are safe by just using
IEnumerable<Test> listT1;
Model1 db = new Model1();
listT1 = db.Tests;
foreach (var a in listT1) //foreach evaluates (but at wrong time)
{
Console.WriteLine(a.value);
}
and never disposing. as it will take care of itself under most circumstances, as thats what it's designed to do.
Now should you open up a connection by force then the context wont close it automatically when the transfer is done, as it don't know when and then you must/should dispose the object or close the connection and keep the object undisclosed.
Extra midnight reading:
http://blog.jongallant.com/2012/10/do-i-have-to-call-dispose-on-dbcontext.html#.U6WdzrGEeTw
https://msdn.microsoft.com/en-us/data/jj729737.aspx

There is no need to explicitly dispose DbContext.
This is an old hold over from pre-DbContext tools. DbContext is managed code and optimistically maintains database connections on its own. Why sledgehammer it? Whats the hurry? Why not just let the garbage collector decide the best time to clean up when the machine is idle or in need of memory? Also refer to this post: https://blog.jongallant.com/2012/10/do-i-have-to-call-dispose-on-dbcontext/
By not worrying about having to dispose will simplify and optimize your code. Typically I might inherit from a database "helper" class to where I use a getter to either return an already existing DbContext instance, or instantiates a new instance. .
public class DataTools
{
private AppContext _context;
protected AppContext Context => _context ?? (_context = new AppContext());
}
pubic class YourApp : DataTools
{
public void DoLotsOfThings()
{
var = Context.SomeTable.Where(s => s.....);
var stuff = GetSomeThing();
foreach(){}
}
Public string GetSomething()
{
return Context.AnotherTable.First(s => s....).Value;
}
}

Related

EF (entity framework) usage of "using" statement

I have a project on MVC. We chose EF for our DB transactions. We created some managers for the BLL layer. I found a lot of examples, where "using" statement is used, i.e.
public Item GetItem(long itemId)
{
using (var db = new MyEntities())
{
return db.Items.Where(it => it.ItemId == itemId && !it.IsDeleted).FirstOrDefault();
}
}
Here we create a new instance of DBcontext MyEntities().
We using "using" in order to "ensure the correct use of IDisposable objects."
It's only one method in my manager. But I have more than ten of them.
Every time I call any method from the manager I'll be using "using" statement and create another DBcontext in the memory. When will the garbage collector (GC) dispose them? Does anyone know?
But there is alternative usage of the manager methods.
We create a global variable:
private readonly MyEntities db = new MyEntities();
and use DBcontext in every method without "using" statement. And method looks like this:
public Item GetItem(long itemId)
{
return db.Items.Where(it => it.ItemId == itemId && !it.IsDeleted).FirstOrDefault();
}
Questions:
What is the proper way of using DBcontext variable?
What if we wouldn't use "usage" statement (because it affects the performance) - GC will do all for that?
I'm a "rookie" in EF usage and still haven't found the unequivocal answer for this question.
I think you will find many suggesting this style of pattern. Not just me or Henk
DBContext handling
Yes, Ideally Using statements for DBContext subtypes
Even better Unit Of Work patterns that are managed with Using, that have a context and dispose the context Just 1 of many UoW examples, this one from Tom Dykstra
The Unit Of Work Manager should be New each Http request
The context is NOT thread safe so make sure each thread has its own context.
Let EF cache things behind the scenes.
Test Context creation times. after several Http request. Do you still have a concern?
Expect problems if you store the context in static. any sort of concurrent access will hurt and if you are using parallel AJAX calls, assume 90+% chance of problems if using a static single context.
For some performance tips, well worth a read
The proper or best practice way of using DBContext variable is with the Using.
using (var db = new MyEntities())
{
return db.Items.Where(it => it.ItemId == itemId && !it.IsDeleted).FirstOrDefault();
}
The benefit is many things are done automatically for us. For example once the block of code is completed the dispose is called.
Per MSDN EF Working with DbContext
The lifetime of the context begins when the instance is created and
ends when the instance is either disposed or garbage-collected. Use
using if you want all the resources that the context controls to be
disposed at the end of the block. When you use using, the compiler
automatically creates a try/finally block and calls dispose in the
finally block.

Suggestions on how to avoid disposing of an object twice

I have a a list of disposable items that I am adding to collection that already contains a number of disposable items. I wrap the code in a try...finally block so that if an exception is thrown while I am copying the items from the list to the collection all the objects in the list get disposed of correctly:
private static void LoadMenuItems(ApplicationMenu parent)
{
List<ApplicationMenuItem> items = null;
try
{
items = DataContext.GetMenuItems(parent.Id);
foreach (var item in items)
{
parent.Items.Add(item);
}
items = null;
}
finally
{
if (items != null)
{
foreach (var item in items)
{
item.Dispose();
}
}
}
}
If an exception occurs after adding a number of the objects to the collection, I'll have a situation where the collection contains some disposed objects. Which could give rise to those disposed objects being disposed of again in the following try...catch block:
try
{
// Assume that menu.Items contains some items prior
// to the call to LoadMenuItems.
LoadMenuItems(menu);
}
catch
{
// The Dispose() iterates through menu.Items calling
// Dispose() on each.
menu.Dispose();
}
So what I am looking for possible solutions to stop Dispose() being called twice. I have a solution in mind, but thought I would give it to the community to see if there are any alternatives.
Which could give rise to those disposed objects being disposed of again
Which should be quite alright. The contract for Dispose() is very specific: it should be safe to call it multiple times.
But another way to get rid of it:
Analyzing your logic I would say the finally part is superfluous, maybe the analyzer thinks so too. You really do solve the same problem twice.
Most cases where one might be worried about "accidentally" disposing an object multiple times come about because there is confusion about who "owns" the object in question, and such confusion will likely create other problems in addition to repeated disposal. While one could avoid having the multiple-disposal itself cause problems by having the disposal method use a flag so the second dispose attempt will return harmlessly, doing that without resolving the confusion about IDisposable ownership would not lave the more serious issues unresolved.
The primary scenarios where repeated disposal attempts should not be regarded as indicating broader problems are
Situations where creation of an object fails with a partially-constructed object; while one could probably define policies as to which parts of a partially-constructed object are responsible for cleaning up which other parts, it may be easier to simply have each part that's told to perform an "emergency" cleanup to tell every part it knows about to do likewise if it hasn't already. In most disposal scenarios, confusions regarding object ownership can result in objects being disposed while still in use, but if an object factory fails, that generally implies that no references to the object have been released to anyone who is going to use them.
Situations where disposal of an object which is in use is a legitimate usage scenario with predictable semantics. For example, some data sources have blocking wait methods, and explicitly specify that disposal of the data source while a blocking method is waiting on it will that method to fail without further delay. In some cases, it may well be that yanking the disposable resource out from under the task that's using it is the only way for such a task to become unstuck.
Your scenario seems somewhat like the first one, except that it looks like you'll be disposing of each item after it gets added to parent.Items, which would suggest that you may have muddled issues of object ownership.

Object disposal in .Net

Assuming i have the following classes:
Class MainClass
{
private OtherClass1;
MainClass()
{
OtherClass1 = new OtherClass1();
}
void dispose()
{
OtherClass1 = null;
}
}
class OtherClass1
{
private OtherClass2;
OtherClass1()
{
OtherClass2 = new OtherClass2();
}
}
class OtherClass2
{
}
If i instatiate MainClass and later call dispose method, does the OtherClass1 gets garbage collected (later on)? Or do i have first to clear the reference to OtherClass2?
An object will get garbage collected if it has no references, or the references it does have are from objects that themselves don't have references (and so on).
A way of visualising it, is the garbage collector will walk the object reference graph, following all object references, making a note of ones it gets to (still referenced from somewhere). Any it doesn't get to are eligible for garbage collection as if it didn't get to them then they can't possibly be used.
See here for in-depth info (particularly "The Garbage Collection Algorithm"): http://msdn.microsoft.com/en-us/magazine/bb985010.aspx
So yes, it'll be eligible to be GC'd.
Also, if you have a dispose method you really should implement IDisposable.
In the code as provided, you don't have to null anything, you can safely remove your dispose() and all will be well.
If your OtherClass1 and/or OtherClass2 are managed resources, ie they implement the IDisposable interface then your code is not good enough. You then will have to chain the Dispose:
class MainClass : IDisposable
{
private OtherClass1;
MainClass()
{
OtherClass1 = new OtherClass1();
}
public void Dispose()
{
OtherClass1.Dispose();
// OtherClass1 = null; // not needed
}
}
If there is no other reference to it, it may at some time be garbage collected. Note that this is not deterministic, you cannot rely on it being collected in a specific timespan.
In general, you shouldn't worry too much abot this, the GC in .NET can by design handle circular references etc. without any problem. Setting fields to null is usually not required. The Dispose method is usually used to release unmanaged resources, such as database connections etc. in a deterministic fashion; it's not about freeing the memory of the object being disposed.
The best practice is to implement IDisposable interface and implementing the Dispose() method.
At Dispose(), you just release the resources used by your object such as any external resources, COM references, database connections, etc.
In terms of When the object will be garbage collected, it's up to the .NET engine to decide that as they frequently update their disposal algorithm with each release.
In general, when an object is orphan (no variable references it), it will be in the queue to be garbage collected.
You can manually call GC.Collect(); but that's not recommended since it interferes .NET garbage collection mechanism.
The term "Dispose" is a bit of a misnomer, since the Dispose method doesn't delete the targeted object but rather serves a request for the targeted object to do anything that will need to be done before it may be safely abandoned. Essentially, it's a request for the object to put its affairs in order.
The most common situation when a particular object will need to put its affairs in order is when some entities outside of it may be doing something, storing something, refraining from doing something, or otherwise temporarily altering their behavior on its behalf. Note that the entities may be .net objects, other types of OS-recognized objects (GDI handles, etc.), etc. but there's no particular requirement that the entity be any particular kind of thing, nor that they be in the same computer, or even any computer. For an object to puts its affairs in order, outside entities doing, holding, etc. anything on its behalf need to be told that they no longer need to do so. If the entities in question are .net objects that implement IDisposable, the notification would be generally performed by calling their Dispose method.
Note that .net provides a means by which objects can ask to be notified if the system notices that they've been abandoned, and use that as a cue to put their affairs in order. Such notifications may not come in timely fashion, and various factors may cause them to be delayed essentially indefinitely, but the mechanism (called "finalization") is sometimes better than nothing.

C# disposable objects

Are there some advices about how I should deal with the IDisposable object sequences?
For example, I have a method that builds a IEnumerable<System.Drawing.Image> sequence and
at some point I would need to dispose that objects manually, because otherwise this might lead to some leaks.
Now, is there a way to bind the Dispose() call to garbage collector actions, because I want these objects disposed right in the moment they are no longer accessible from other code parts?
**Or maybe you could advice me some other approach? **
Generally, this seems to be the same problem as it comes, for example, in unmanaged C++ without shared pointers, where you can have a method:
SomeObject* AllocateAndConstruct();
and then you can't be sure when to dispose it, if you don't use code contracts or don't state something in the comments.
I guess the situation with disposable objects is pretty the same, but I hope there is an appropriate solution for this.
(from the question)
Now, is there a way to bind the
Dispose() call to garbage collector
actions, because I want these objects
disposed right in the moment they are
no longer accessible from other code
parts?
GC doesn't happen immediately when your object goes out of scope / reach; it is non-deterministic. By the time GC sees it, there is no point doing anything else (that isn't already handled by the finalizer), as it is too late.
The trick, then, is to know when you are done with it, and call Dispose() yourself. In many cases using achieves this. For example you could write a class that implements IDisposable and encapsulates a set of Images - and wrap your use of that encapsulating object with using. The Dispose() on the wrapper could Dispose() all the images held.
i.e.
using(var imageWrapper = GetImages()) {
foreach(var image in imageWrapper) {
...
}
// etc
} // assume imageWrapper is something you write, which disposes the child items
however, this is a bit trickier if you are displaying the data on the UI. There is no shortcut there; you will have to track when you are done with each image, or accept non-deterministic finalization.
If you want to determiniscally dispose of the objects in the collection, you should call Dispose on each:
myImages.ToList().ForEach(image => image.Dispose());
If you don't do this, and if your objects become unreachable, the GC will eventually run and release them.
Now, if you don't want to manually code the Dispose calls, you can create a wrapper class that implements IDisposable and use it through a using statement:
using (myImages.AsDisposable()) {
// ... process the images
}
This is the needed "infrastructure":
public class DisposableCollectionWrapper<D> : IDisposable
where D : IDisposable {
private readonly IEnumerable<D> _disposables;
public DisposableCollectionWrapper(IEnumerable<D> disposables) {
_disposables = disposables;
}
public void Dispose() {
if (_disposables == null) return;
foreach (var disposable in _disposables) {
disposable.Dispose();
}
}
}
public static class CollectionExtensions {
public static IDisposable AsDisposable<D>(this IEnumerable<D> self)
where D : IDisposable {
return new DisposableCollectionWrapper<D>(self);
}
}
Also notice that this is not the same as the situation you described with C++. In C++, if you don't delete your object, you have a genuine memory leak. In C#, if you don't dispose of your object, the garbage collector will eventually run and clean it up.
You should design your system in a way that you know when the resources are no longer needed. In the worst case, they'll be eventually disposed when the garbage collector gets to it, but the point of IDisposable is that you can release important resources earlier.
This "earlier" is up to you to define, for example, you can release them when the window that's using them closes, or when your unit of work finishes doing whatever operations on them. But at some point, some object should "own" these resources, and therefore should know when they're no longer needed.
You can use the 'using' block, to make sure, the IDisposable is disposed as soon the block is left. The compiler does encapsulate such blocks into try - finally statements in order to make sure, Dispose is called in any case when leaving the block.
By using a finalizer, one can make the GC call the Dispose method for those objects which where "missed" somehow. However, implementing a finalizer is more expensive and decreases the garbage collection efficiency - and possibly the overall performance of your application. So if any possible, you should try to make sure to dispose your IDisposables on your own; deterministically:
public class Context : IDisposable {
List<IDisposable> m_disposable = new List<IDisposable>();
public void AddDisposable(IDisposable disposable) {
m_disposable.Add(disposable);
}
public void Dispose() {
foreach (IDisposable disp in m_disposable)
disp.Dispose();
}
// the Context class is used that way:
static void Main(string[] args) {
using (Context context = new Context()) {
// create your images here, add each to the context
context.AddDisposable(image);
// add more objects here
} // <- leaving the scope will dispose the context
}
}
By using some clever design, the process of adding objects to the context may can get even more easier. One might give the context to the creation method or publish it via a static singleton. That way, it would be available for child method scopes as well - without having to pass a reference to the contex around. By utilizing that scheme it is even possible, to simulate an artificial destructor functionality like f.e. known from C++.
The neat method would be to create your own generic collection class that implements IDisposable. When this collection class is Disposed() ask for each element if it implements IDisposed, and if so Dispose it.
Example (look elsewhere if you don't know about the IDisposable pattern)
public class MyDisposableList<T> : List<T> : IDisposable
{
private bool disposed = false;
~MyDisposableList()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
}
protected void Dispose(bool disposing)
{
if (!disposed)
{
foreach (T myT in this)
{
IDisposable myDisposableT = myT as IDisposable;
if (myDisposableT != null)
{
myDisposableT.Dispose();
}
myT = null;
}
this.Clear();
this.TrimExcess();
disposed = true;
}
}
...
}
usage:
using (MyDisposableList<System.Drawing.Bitmap> myList = new ...)
{
// add bitmaps to the list (bitmaps are IDisposable)
// use the elements in the list
}
The end of the using statement automatically Disposes myList, and thus all bitMaps in myList
By the way: if you loaded the bitmap from a file and you forgot to Dispose() the bitmap you don't know when you can delete that file.
You can call GC.Collect() if you really was to dispose those objects right away but to my understanding it is up to the GC to decide whether to collect the memory.
This in turn will call the Finalize() method for each object that should be released.
Note that if the collection goes out of scope the GC will eventually collect the memory used by the images.
You can also use the using construct if you use a collection that implements IDisposeable. That will guarantee that the objects will be disposed exactly when the collection goes out of scope (or nearly after the end of the scope).

Generic function to handle disposing IDisposable objects

I am working on a class that deals with a lot of Sql objects - Connection, Command, DataAdapter, CommandBuilder, etc. There are multiple instances where we have code like this:
if( command != null )
{
command.Dispose();
}
if( dataAdapter != null )
{
dataAdapter.Dispose();
}
etc
I know this is fairly insufficient in terms of duplication, but it has started smelling. The reason why I think it smells is because in some instances the object is also set to null.
if( command != null )
{
command.Dispose();
command = null;
}
I would love to get rid of the duplication if possible. I have come up with this generic method to dispose of an object and set it to null.
private void DisposeObject<TDisposable>( ref TDisposable disposableObject )
where TDisposable : class, IDisposable
{
if( disposableObject != null )
{
disposableObject.Dispose();
disposableObject = null;
}
}
My questions are...
Is this generic function a bad idea?
Is it necessary to set the object to null?
EDIT:
I am aware of the using statement, however I cannot always use it because I have some member variables that need to persist longer than one call. For example the connection and transaction objects.
Thanks!
You should consider if you can use the using statement.
using (SqlCommand command = ...)
{
// ...
}
This ensures that Dispose is called on the command object when control leaves the scope of the using. This has a number of advantages over writing the clean up code yourself as you have done:
It's more concise.
The variable will never be set to null - it is declared and initialized in one statement.
The variable goes out of scope when the object is disposed so you reduce the risk of accidentally trying to access a disposed resource.
It is exception safe.
If you nest using statements then the resources are naturally disposed in the correct order (the reverse order that they were created in).
Is it necessary to set the object to null?
It is not usually necessary to set variables to null when you have finished using them. The important thing is that you call Dispose when you have finished using the resource. If you use the above pattern, it is not only unnecessary to set the variable to null - it will give a compile error:
Cannot assign to 'c' because it is a 'using variable'
One thing to note is that using only works if an object is acquired and disposed in the same method call. You cannot use this pattern is if your resources need to stay alive for the duration of more than one method call. In this case you might want to make your class implement IDisposable and make sure the resources are cleaned up when your Dispose method is called. I this case you will need code like you have written. Setting variables to null is not wrong in this case but it is not important because the garbage collector will clean up the memory correctly anyway. The important thing is to make sure all the resources you own are disposed when your dispose method is called, and you are doing that.
A couple of implementation details:
You should ensure that if your Dispose is called twice that it does not throw an exception. Your utility function handles this case correctly.
You should ensure that the relevant methods on your object raise an ObjectDisposedException if your object has already been disposed.
You should implement IDisposable in the class that owns these fields. See my blog post on the subject. If this doesn't work well, then the class is not following OOP principles, and needs to be refactored.
It is not necessary to set variables to null after disposing them.
If you're objects have a lot of cleanup to do, they might want to track what needs to be deleted in a separate list of disposables, and handle all of them at once. Then at teardown it doesn't need to remember everything that needs to be disposed (nor does it need to check for null, it just looks in the list).
This probably doesn't build, but for expanatory purposes, you could include a RecycleBin in your class. Then the class only needs to dispose the bin.
public class RecycleBin : IDisposable
{
private List<IDisposable> _toDispose = new List<IDisposable>();
public void RememberToDispose(IDisposable disposable)
{
_toDispose.Add(disposable);
}
public void Dispose()
{
foreach(var d in _toDispose)
d.Dispose();
_toDispose.Clear();
}
}
I assume these are fields and not local variables, hence why the using keyword doesn't make sense.
Is this generic function a bad idea?
I think it's a good idea, and I've used a similar function a few times; +1 for making it generic.
Is it necessary to set the object to null?
Technically an object should allow multiple calls to its Dispose method. (For instance, this happens if an object is resurrected during finalization.) In practice, it's up to you whether you trust the authors of these classes or whether you want to code defensively. Personally, I check for null, then set references to null afterwards.
Edit: If this code is inside your own object's Dispose method then failing to set references to null won't leak memory. Instead, it's handy as a defence against double disposal.
I'm going to assume that you are creating the resource in one method, disposing it in another, and using it in one or more others, making the using statement useless for you.
In which case, your method is perfectly fine.
As far the second part of your question ("Is setting it to null necessary?"), the simple answer is "No, but it's not hurting anything".
Most objects hold one resource -- memory, which the Garbage collection deals with freeing, so we don't have to worry about it. Some hold some other resource as well : a file handle, a database connection, etc. For the second category, we must implement IDisposable, to free up that other resource.
Once the Dispose method is called, both categories because the same : they are holding memory. In this case, we can just let the variable go out of scope, dropping the reference to the memory, and allowing to GC to free it eventually -- Or we can force the issue, by setting the variable to null, and explicitly dropping the reference to the memory. We still have to wait until the GC kicks in for the memory to actually be freed, and more than likely the variable will go out of scope anyway, moments after to set it to null, so in the vast majority of cases, it will have no effect at all, but in a few rare cases, it will allow the memory to be freed a few seconds earlier.
However, if your specific case, where you are checking for null to see if you should call Dispose at all, you probably should set it to null, if there is a chance you might call Dispose() twice.
Given that iDisposable does not include any standard way of determining whether an object has been disposed, I like to set things to null when I dispose of them. To be sure, disposing of an object which has already been disposed is harmless, but it's nice to be able to examine an object in a watch window and tell at a glance which fields have been disposed. It's also nice to be able to have code test to ensure that objects which should have been disposed, are (assuming the code adheres to the convention of nulling out variables when disposing of them, and at no other time).
Why don't you use using C# construct? http://msdn.microsoft.com/en-us/library/yh598w02.aspx
Setting to null if not required.
Others have recommended the using construct, which I also recommend. However, I'd like to point out that, even if you do need a utility method, it's completely unnecessary to make it generic in the way that you've done. Simply declare your method to take an IDisposable:
private static void DisposeObject( ref IDisposable disposableObject )
{
if( disposableObject != null )
{
disposableObject.Dispose();
disposableObject = null;
}
}
You never need to set variables to null. The whole point of IDisposable.Dispose is to get the object into a state whereby it can hang around in memory harmlessly until the GC finalises it, so you just "dispose and forget".
I'm curious as to why you think you can't use the using statement. Creating an object in one method and disposing it in a different method is a really big code smell in my book, because you soon lose track of what's open where. Better to refactor the code like this:
using(var xxx = whatever()) {
LotsOfProcessing(xxx);
EvenMoreProcessing(xxx);
NowUseItAgain(xxx);
}
I'm sure there is a standard pattern name for this, but I just call it "destroy everything you create, but nothing else".
I answered this in my question and answer here:
Implementing IDisposable (the Disposable Pattern) as a service (class member)
It implemented a simplistic, reusable component that works for any IDisposable member.

Categories