How can I create a System Mutex in C#

后端 未结 3 1349
谎友^
谎友^ 2020-12-10 13:18

How can I create a system/multiprocess Mutex to co-ordinate multiple processes using the same unmanaged resource.

Background: I\'ve written a procedure that uses

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-10 13:25

    I have not had good luck using the System Mutex described above using Mono under Linux. I'm probably just doing something simple wrong but the following works well and cleans up nicely if the process exits unexpectedly (kill -9 ). Would would be interested to hear comments or critisisms.

    class SocketMutex{
        private Socket _sock;
        private IPEndPoint _ep;
        public SocketMutex(){
            _ep = new IPEndPoint(IPAddress.Parse( "127.0.0.1" ), 7177);
            _sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            _sock.ExclusiveAddressUse = true;  // most critical if you want this to be a system wide mutex
        }
    
        public bool GetLock(){
            try{        
                _sock.Bind(_ep); // 'SocketException: Address already in use'
            }catch(SocketException se){
                Console.Error.WriteLine ("SocketMutex Exception: " se.Message);
                return false;
            }
            return true;
    
        }
    }
    

提交回复
热议问题