VolumeHandlePool.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /* Copyright (C) 2014 Tal Aloni <tal.aloni.il@gmail.com>. All rights reserved.
  2. *
  3. * You can redistribute this program and/or modify it under the terms of
  4. * the GNU Lesser Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. */
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Text;
  11. using Microsoft.Win32.SafeHandles;
  12. using Utilities;
  13. namespace DiskAccessLibrary
  14. {
  15. public class VolumeHandlePool
  16. {
  17. // We will use the handle pool to share handles to volumes across the application (useful when handle need to lock access to a volume)
  18. private static Dictionary<Guid, SafeFileHandle> m_handlePool = new Dictionary<Guid, SafeFileHandle>();
  19. /// <param name="newAllocation">True if a new handle has been allocated for the caller, the caller must release the handle eventually</param>
  20. public static SafeFileHandle ObtainHandle(Guid volumeGuid, FileAccess access, ShareMode shareMode, out bool newAllocation)
  21. {
  22. if (m_handlePool.ContainsKey(volumeGuid))
  23. {
  24. newAllocation = false;
  25. return m_handlePool[volumeGuid];
  26. }
  27. else
  28. {
  29. newAllocation = true;
  30. SafeFileHandle handle = HandleUtils.GetVolumeHandle(volumeGuid, access, shareMode);
  31. m_handlePool.Add(volumeGuid, handle);
  32. return handle;
  33. }
  34. }
  35. public static bool ReleaseHandle(Guid volumeGuid)
  36. {
  37. if (m_handlePool.ContainsKey(volumeGuid))
  38. {
  39. SafeFileHandle handle = m_handlePool[volumeGuid];
  40. if (!handle.IsClosed)
  41. {
  42. handle.Close();
  43. }
  44. m_handlePool.Remove(volumeGuid);
  45. return true;
  46. }
  47. else
  48. {
  49. return false;
  50. }
  51. }
  52. }
  53. }