Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abuse using and Dispose() for scope handling of not to be released objects?

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?

like image 959
FrankU Avatar asked Aug 07 '13 18:08

FrankU


2 Answers

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
like image 149
Sergey Kalinichenko Avatar answered Sep 24 '22 10:09

Sergey Kalinichenko


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.

like image 40
Oded Avatar answered Sep 25 '22 10:09

Oded