最近在学习SharpDevelop源代码,看到一处访问文件的很有美感的代码,特此供大家一起分享:
public sealed class CallbackOnDispose : IDisposable { Action callback; public CallbackOnDispose(Action callback) { if (callback == null) throw new ArgumentNullException("callback"); this.callback = callback; } public void Dispose() { Action action = Interlocked.Exchange(ref callback, null); if (action != null) { action(); #if DEBUG GC.SuppressFinalize(this); #endif } } #if DEBUG ~CallbackOnDispose() { Debug.Fail("CallbackOnDispose was finalized without being disposed."); } #endif }
此处定义一个实现IDisposable接口的回调方法的类。调用的时候如下:
using (LockPropertyFile())
{ using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
{ ms.WriteTo(fs); } }
public static IDisposable LockPropertyFile() { Mutex mutex = new Mutex(false); mutex.WaitOne(); return new CallbackOnDispose( delegate { mutex.ReleaseMutex(); mutex.Close(); }); }