CanonicalDisposableStruct.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /* Copyright 2010-2014 MongoDB Inc.
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. using System;
  16. namespace MongoDB.Shared
  17. {
  18. /// <summary>
  19. /// Represents a struct that owns one or more disposable resources.
  20. /// </summary>
  21. public struct CanonicalDisposableStruct : IDisposable
  22. {
  23. // private fields
  24. private bool _disposed;
  25. private IDisposable _disposableResource;
  26. /// <summary>
  27. /// Initializes a new instance of the <see cref="CanonicalDisposableStruct"/> struct.
  28. /// </summary>
  29. /// <param name="disposableResource">A disposable resource.</param>
  30. public CanonicalDisposableStruct(IDisposable disposableResource)
  31. {
  32. _disposed = false;
  33. _disposableResource = disposableResource;
  34. }
  35. // NOTE: structs can't have finalizers
  36. // public methods
  37. /// <summary>
  38. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  39. /// </summary>
  40. public void Dispose()
  41. {
  42. Dispose(true);
  43. // no need to call GC.SuppressFinalize for structs
  44. }
  45. /// <summary>
  46. /// Some method.
  47. /// </summary>
  48. public void SomeMethod()
  49. {
  50. ThrowIfDisposed();
  51. // ...
  52. }
  53. // private methods
  54. private void Dispose(bool disposing)
  55. {
  56. // this method can be called multiple times
  57. // make sure your implementation of this method does not throw any exceptions
  58. if (!_disposed)
  59. {
  60. if (disposing)
  61. {
  62. // dispose of any managed disposable resources you own here
  63. if (_disposableResource != null)
  64. {
  65. _disposableResource.Dispose();
  66. _disposableResource = null; // not strictly necessary but a good idea
  67. }
  68. }
  69. // dispose of any unmanaged resources here
  70. _disposed = true;
  71. }
  72. }
  73. private void ThrowIfDisposed()
  74. {
  75. if (_disposed)
  76. {
  77. throw new ObjectDisposedException(GetType().Name);
  78. }
  79. }
  80. }
  81. }