Advertisement
NPSF3000

SafetyFramework

Sep 12th, 2012
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.28 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7.  
  8. namespace StructException
  9. {
  10.     class Program
  11.     {
  12.         static void Main(string[] args)
  13.         {
  14.             Test t;
  15.             try
  16.             {
  17.                 t = new Test();
  18.             }
  19.             catch (Exception e)
  20.             {
  21.                 Console.WriteLine(e.Message);
  22.             }
  23.  
  24.             Console.ReadLine();
  25.         }
  26.     }
  27.  
  28.     class Test : SafetyFramework
  29.     {
  30.         // Something contains a thread or socket descriptor so must be cleaned up.
  31.         FileStream fs;
  32.         public Test()
  33.         {
  34.             Safe(() => fs = new FileStream("ErrorOut", FileMode.Open));
  35.         }
  36.  
  37.         public override void Dispose()
  38.         {
  39.             Console.WriteLine("Disposing FS");
  40.             if (fs != null) fs.Dispose();
  41.         }
  42.     };
  43.  
  44.     public class SafetyFramework : IDisposable
  45.     {
  46.         protected void Safe(Action a)
  47.         {
  48.             try
  49.             {
  50.                 a();
  51.             }
  52.             catch
  53.             {
  54.                 Dispose();
  55.                 throw;
  56.             }
  57.         }
  58.  
  59.         public virtual void Dispose()
  60.         {
  61.         }
  62.     }
  63.  
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement