最近在学习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();
                });
        }

 

 

转载于:https://www.cnblogs.com/Johnnie/p/3768590.html

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐