For convenience and safety reasons i'd like to use the using
statement for allocation and release of objects from/to a pool
public class Resource : IDisposable
{
public void Dispose()
{
ResourcePool.ReleaseResource(this);
}
}
public class ResourcePool
{
static Stack<Resource> pool = new Stack<Resource>();
public static Resource GetResource()
{
return pool.Pop();
}
public static void ReleaseResource(Resource r)
{
pool.Push(r);
}
}
and the access the pool like
using (Resource r = ResourcePool.GetResource())
{
r.DoSomething();
}
I found some topics on abusing using
and Dispose()
for scope handling but all of them incorporate using (Blah b = _NEW_ Blah())
.
Here the objects are not to be freed after leaving the using scope but kept in the pool.
If the using statement simply expands to a plain try finally Dispose()
this should work fine but is there something more happening behind the scenes or a chance this won't work in future .Net versions?
This is not an abuse at all - that is a common scope-handling idiom of C#. For example, ADO.NET objects (connections, statements, query results) are commonly enclosed in using
blocks, even though some of these objects get released back to their pools inside their Dispose
methods:
using (var conn = new SqlConnection(dbConnectionString)) {
// conn is visible inside this scope
...
} // conn gets released back to its connection pool
It is a valid way to use IDisposable
.
In fact, this is how connection pooling is also done in .NET - wrapping a DBConnection
object in a using
statement to ensure the connection closes and is returned to the connection pool.
TransactionScope
is another example for a class that uses the Dispose
pattern to rollback un-completed transactions:
A call to the Dispose method marks the end of the transaction scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With