一個C#的加鎖解鎖示例


大家可以仿照這個方法做:
 
using   System; 
using   System.Collections.Generic; 
using   System.Text; 

namespace   Generic_Reusable 

        interface   ILockable 
        { 
                void   Lock(); 
                void   Unlock(); 
        } 

        class   SharedMemoryLock   :   ILockable 
        { 
                #region   ILockable   Members 

                public   void   Lock() 
                { 
                        Console.WriteLine( "SharedLock   performs   lock   method. "); 
                } 

                public   void   Unlock() 
                { 
                        Console.WriteLine( "SharedLock   performs   unlock   method. "); 
                } 

                #endregion 
        } 

        class   FileLock   :   ILockable 
        { 
                #region   ILockable   Members 

                public   void   Lock() 
                { 
                        Console.WriteLine( "FileLock   performs   lock   method. "); 
                } 

                public   void   Unlock() 
                { 
                        Console.WriteLine( "FileLock   performs   unlock   method. "); 
                } 

                #endregion 
        } 

        class   ReusableLock <LOCK >   :   ILockable   where   LOCK   :   ILockable,   new() 
        { 
                private   LOCK   lock__   =   new   LOCK(); 

                #region   ILockable   Members 

                public   void   Lock() 
                { 
                        lock__.Lock(); 
                } 

                public   void   Unlock() 
                { 
                        lock__.Unlock(); 
                } 

                #endregion 
        } 

        class   Program 
        { 
                static   void   Main(string[]   args) 
                { 
                        try 
                        { 
                                ReusableLock <SharedMemoryLock >   theLock   =   new   ReusableLock <SharedMemoryLock >(); 
                                theLock.Lock(); 
                                //   TODO:   Add   your   code   here 
                                theLock.Unlock(); 
                        } 
                        catch   (Exception   ex) 
                        { 
                                Console.WriteLine(ex.Message); 
                        } 
                } 
        } 
作者: XuGang   網名:鋼鋼
出處: http://xugang.cnblogs.com
聲明: 本文版權歸作者和博客園共有。轉載時必須保留此段聲明,且在文章頁面明顯位置給出原文連接地址!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM