Generic processing of a Drag event from the file system

This is an extension method to help a user in processing a DragEventArgs to a object type of their choice.

How

  • Take a function to create the required Type from a FileStream.
  • Take an Action to handle an exception.
  • Check that the drop array contains a FileDrop.
  • Select the First FileInfo and open a FileStream.
  • Execute createAction with this FileStream. If this fails the exception will be handled by the onFailed callback.

The Code:

A generic pool of objects

Right as this is my first post let’s keep it nice and simple.

A pool works by managing a collection of objects kept in memory so they are always available. A pool can be particularly useful for many situations such as managing large classes which take time to initialise and can help contain classes with memory leaks. There is no correct way to make a pool and it should be optimised to the requirements of the situation.

This pool is designed to recycle a collection of objects:

  • It creates a new object of type T when it is empty.
  • It is important that we only store ONE reference to each instance of an object in the collection, hence the validation in the ReturnToPool() method.
  • The lock() method is used to make this class threadsafe.
  • In most instances such as managing a memory leak, it should be used as a singleton.
  • When an object is ready to be returned it is not the responsibility of this class to do so. (I will make a post in the future about correct ways to do this)
The code:
public class Pool<T>
{
    private readonly Stack<T> _pool = new Stack<T>();
    private readonly Func<T> _createNewFunction;

    public Pool(Func<T> createNewFunction)
    {
        _createNewFunction = createNewFunction;
    }

    public T GetFromPool()
    {
        lock (_pool)
        {
            if (_pool.Count <= 0)
            {
                // Create a new T
                return _createNewFunction();
            }

            return _pool.Pop();
        }
    }

    public void ReturnToPool(T item)
    {
        lock (_pool)
        {
            if (_pool.Contains(item))
            {
                // If it is already in the pool don't re-add it.
                throw new InvalidOperationException("This item is already in the pool");
            }

            _pool.Push(item);
        }
    }
}
Return top