code_junkie

How to do C++ style destructors in C#?

Nov 10th, 2011
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.32 KB | None | 0 0
  1. try
  2. {
  3. PleaseDisposeMe a = new PleaseDisposeMe();
  4. throw new Exception();
  5. a.Dispose();
  6. }
  7. catch (Exception ex)
  8. {
  9. Log(ex);
  10. }
  11.  
  12. // This next call will throw a time-out exception unless the GC
  13. // runs a.Dispose in time.
  14. PleaseDisposeMe b = new PleaseDisposeMe();
  15.  
  16. class MyDisposable: IDisposable {
  17. public void Dispose() {
  18. lock(this) {
  19. if (disposed) {
  20. return;
  21. }
  22.  
  23. disposed = true;
  24. }
  25.  
  26. GC.SuppressFinalize(this);
  27.  
  28. // Do actual disposing here ...
  29. }
  30.  
  31. private bool disposed = false;
  32. }
  33.  
  34. ~ClassName()
  35. {
  36. }
  37.  
  38. public class DisposableFinalisableClass : IDisposable
  39. {
  40. ~DisposableFinalisableClass()
  41. {
  42. Dispose(false);
  43. }
  44.  
  45. public void Dispose()
  46. {
  47. Dispose(true);
  48. }
  49.  
  50. protected virtual void Dispose(bool disposing)
  51. {
  52. if (disposing)
  53. {
  54. // tidy managed resources
  55. }
  56.  
  57. // tidy unmanaged resources
  58. }
  59. }
  60.  
  61. using (SqlConnection con = new SqlConnection("DB con str") )
  62. using (SqlCommand com = new SqlCommand( con, "sql query") )
  63. {
  64. //now code is indented one level
  65. //technically we're nested twice
  66. }
  67.  
  68. PleaseDisposeMe a;
  69. try
  70. {
  71. a = new PleaseDisposeMe();
  72. throw new Exception();
  73. }
  74. catch (Exception ex) { Log(ex); }
  75. finally {
  76. //this always executes, even with the exception
  77. a.Dispose();
  78. }
Add Comment
Please, Sign In to add comment