//ライセンス情報はAgeOnフォルダのLISENCEフォルダを参照してください
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace nispi
{
    class AgeonMutex
    {
        public Mutex mutex;
        public bool close;

        public AgeonMutex()
        {
            close = false;
        }

        public void Init()
        {
            string num = GetRandamStr();
            mutex = new Mutex(false, num);
        }

        public void Terminate()
        {
            close = true;
            mutex.Close();
            //mutex.Dispose();
        }

        public bool WaitOne()
        {
            try
            {
                mutex.WaitOne();
                if (close == true)
                {
                    //mutex.ReleaseMutex();
                    return false;
                }
                else
                {
                    //mutex.ReleaseMutex();
                    return true;
                }
            }
            catch
            {
                return false;
            }
        }

        public void ReleaseMutex()
        {
            try
            {
                mutex.ReleaseMutex();
            }
            catch { ;}
        }
        //参考：http://dobon.net/vb/dotnet/programing/random.html
        public string GetRandamStr()
        {
            byte[] bs = new byte[4];
            System.Security.Cryptography.RNGCryptoServiceProvider rng =
                new System.Security.Cryptography.RNGCryptoServiceProvider();
            rng.GetBytes(bs);

            return System.BitConverter.ToInt32(bs, 0).ToString();
        }
    }
}
