Exemplo n.º 1
0
    public static void BilinearScale(System.Object obj)
    {
        ThreadData threadData = (ThreadData)obj;

        for (var y = threadData.start; y < threadData.end; y++)
        {
            int yFloor = (int)Mathf.Floor(y * ratioY);
            var y1     = yFloor * w;
            var y2     = (yFloor + 1) * w;
            var yw     = y * w2;

            for (var x = 0; x < w2; x++)
            {
                int xFloor = (int)Mathf.Floor(x * ratioX);
                var xLerp  = x * ratioX - xFloor;
                newColors[yw + x] = ColorLerpUnclamped(ColorLerpUnclamped(texColors[y1 + xFloor], texColors[y1 + xFloor + 1], xLerp),
                                                       ColorLerpUnclamped(texColors[y2 + xFloor], texColors[y2 + xFloor + 1], xLerp),
                                                       y * ratioY - yFloor);
            }
        }

        mutex.WaitOne();
        finishCount++;
        mutex.ReleaseMutex();
    }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            const int    population   = 100;                                                                                      //The total population limit and number of initial solutions.
            const int    iterations   = 100000;                                                                                   //The total number of iterations.
            const int    elites       = 2;                                                                                        //The total number of most optimal solutions to bypass tournament selection at each iteration.
            const double mutationRate = .7;                                                                                       //The chance of a randomly sized portion of cities being shuffled when producing a child.

            List <Circuit> individuals = new List <Circuit>();                                                                    //Contains the population.
            Random         random      = new Random();                                                                            //Used for random number generation.
            Mutex          writeAccess = new System.Threading.Mutex();                                                            //Control access to standard output.

            Task.Run(() => { Console.ReadLine(); writeAccess.WaitOne(); individuals.First().PrintPath(); Environment.Exit(0); }); //Listen for early exit sequence.

            for (int i = 0; i < population; i++)
            {
                individuals.Add(new Circuit().Initialize());
            }
            double latestDistance = individuals.Min(i => i.Distance);

            for (int i = 0; i < iterations; i++)
            {
                individuals = individuals.OrderBy(c => c.Distance).ToList(); //This will allow us to match the best with the worst.
                #region User Interaction
                writeAccess.WaitOne();
                Console.WriteLine(individuals.First().Distance);
                writeAccess.ReleaseMutex();
                if (individuals.First().Distance != latestDistance)
                {
                    latestDistance = individuals.First().Distance;
                    Task.Run(() => Console.Beep()); //Beep asynchrnously so you don't slow the program down.
                }
                #endregion User Interaction
                for (int j = 0; j < population; j++)
                {
                    //Create children from two parents. Note the "*" operator.
                    Circuit child = individuals[j] * individuals[(population - 1) - j];
                    //Roll for mutation. Randomly select a contiguous range of elements to permute.
                    if (random.NextDouble() < mutationRate)
                    {
                        int upperBound = random.Next(0, child.Path.Count);
                        int lowerBound = random.Next(0, upperBound);
                        child.Path = child.Path.PermutePart(lowerBound, upperBound);
                    }
                    individuals.Add(child);
                }
                List <Circuit> nextGeneration = new List <Circuit>();
                //Elites bypass and are excluded from selection.
                nextGeneration.AddRange(individuals.OrderBy(i => i.Distance).Take(elites));
                individuals = individuals.OrderBy(i => i.Distance).TakeLast(individuals.Count - elites).ToList();
                //Non-elites participate in tournament selection with replacement.
                for (int j = 0; j < population - elites; j++)
                {
                    nextGeneration.Add(individuals.RandomChoice() - individuals.RandomChoice());
                }
                individuals = nextGeneration;
            }
            individuals = individuals.OrderBy(c => c.Distance).ToList();
            Console.WriteLine(individuals.First().Distance);
            individuals.First().PrintPath();
        }
 void Update()
 {
     StateMutex.WaitOne();
     if (Bodies_ != null && BodyAdjustments_ != null)
     {
         foreach (System.Collections.Generic.KeyValuePair <string, Body_> kv in Bodies_)
         {
             bool adjustmentMade = false;
             foreach (System.Collections.Generic.KeyValuePair <string, Body_> adjustment in BodyAdjustments_)
             {
                 if (kv.Key == adjustment.Key)
                 {
                     InputBroker.SetPosition(kv.Key, new Vector3(
                                                 kv.Value.translation.x + adjustment.Value.translation.x,
                                                 kv.Value.translation.y + adjustment.Value.translation.y,
                                                 kv.Value.translation.z + adjustment.Value.translation.z));
                     Quaternion q = new Quaternion(kv.Value.quaternion.x, kv.Value.quaternion.y, kv.Value.quaternion.z, kv.Value.quaternion.w) *
                                    Quaternion.Euler(adjustment.Value.euler.p, adjustment.Value.euler.h, adjustment.Value.euler.r);
                     InputBroker.SetRotation(kv.Key, q);
                     adjustmentMade = true;
                 }
                 if (!adjustmentMade)
                 {
                     InputBroker.SetPosition(kv.Key, new Vector3(kv.Value.translation.x, kv.Value.translation.y, kv.Value.translation.z));
                     Quaternion q = new Quaternion(kv.Value.quaternion.x, kv.Value.quaternion.y, kv.Value.quaternion.z, kv.Value.quaternion.w);
                     InputBroker.SetRotation(kv.Key, q);
                 }
             }
         }
     }
     StateMutex.ReleaseMutex();
 }
Exemplo n.º 4
0
 private static void Inc()
 {
     for (int i = 0; i < 1000000; i++)
     {
         _mutex.WaitOne();
         value++;
         _mutex.ReleaseMutex();
     }
 }
Exemplo n.º 5
0
        /// <summary>
        /// Loads any additional static information from the file
        /// <param name="session">The session this is part of</param>
        /// </summary>
        public virtual void LoadStaticData(StockSession session)
        {
            var loadMethod = session.Scripts[session].GetStaticMethod("*.Load", File);

            FileMutex.WaitOne();
            File.Seek(LoadAddress, SeekOrigin.Begin);
            loadMethod(File);
            FileMutex.ReleaseMutex();
        }
Exemplo n.º 6
0
 // Update is called once per frame
 void Update()
 {
     StateMutex.WaitOne();
     foreach (System.Collections.Generic.KeyValuePair <string, WiimoteInfo> kv in Wiimotes)
     {
         parsekeys(kv.Key, kv.Value.ButtonState);
         parseaccel(kv.Key, kv.Value.AccelState);
     }
     StateMutex.ReleaseMutex();
 }
        static void Main(string[] args)
        {
            // create the synch primitive
            Mutex mutex = new Mutex();

            // create a cancellation token source
            CancellationTokenSource tokenSource = new CancellationTokenSource();

            // create a task that acquires and releases the mutex
            Task task1 = new Task(() => {
                while (true) {
                    mutex.WaitOne();
                    Console.WriteLine("Task 1 acquired mutex");
                    // wait for 500ms
                    tokenSource.Token.WaitHandle.WaitOne(500);
                    // exit the mutex
                    mutex.ReleaseMutex();
                    Console.WriteLine("Task 1 released mutex");
                }
            }, tokenSource.Token);

            // create a task that acquires and then abandons the mutex
            Task task2 = new Task(() => {
                // wait for 2 seconds to let the other task run
                tokenSource.Token.WaitHandle.WaitOne(2000);
                // acquire the mutex
                mutex.WaitOne();
                Console.WriteLine("Task 2 acquired mutex");
                // abandon the mutex
                throw new Exception("Abandoning Mutex");
            }, tokenSource.Token);

            // start the tasks
            task1.Start();
            task2.Start();

            // put the main thread to sleep
            tokenSource.Token.WaitHandle.WaitOne(3000);

            // wait for task 2
            try {
                task2.Wait();
            } catch (AggregateException ex) {
                ex.Handle((inner) => {
                    Console.WriteLine(inner);
                    return true;
                });
            }

            // wait for input before exiting
            Console.WriteLine("Press enter to finish");
            Console.ReadLine();
        }
Exemplo n.º 8
0
        public ParameterValuePredictor(ITelemetryClient telemetryClient, IAzContext azContext)
        {
            Validation.CheckArgument(telemetryClient, $"{nameof(telemetryClient)} cannot be null.");

            _telemetryClient = telemetryClient;
            _azContext       = azContext;

            var       fileInfo        = new FileInfo(typeof(Settings).Assembly.Location);
            var       directory       = fileInfo.DirectoryName;
            var       mappingFilePath = Path.Join(directory, "command_param_to_resource_map.json");
            Exception exception       = null;

            try
            {
                _commandParamToResourceMap = JsonSerializer.Deserialize <Dictionary <string, Dictionary <string, string> > >(File.ReadAllText(mappingFilePath), JsonUtilities.DefaultSerializerOptions);
            }
            catch (Exception e)
            {
                // We don't want it to crash the module when the file doesn't exist or when it's mal-formatted.
                exception = e;
            }
            _telemetryClient.OnLoadParameterMap(new ParameterMapTelemetryData(exception));

            String path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

            string[] paths = new string[] { path, "Microsoft", "Windows", "PowerShell", "AzPredictor", "paramValueHistory.json" };
            _paramValueHistoryFilePath = System.IO.Path.Combine(paths);
            Directory.CreateDirectory(Path.GetDirectoryName(_paramValueHistoryFilePath));

            Task.Run(() =>
            {
                if (System.IO.File.Exists(_paramValueHistoryFilePath))
                {
                    _mutex.WaitOne();
                    try
                    {
                        var localParameterValues = JsonSerializer.Deserialize <ConcurrentDictionary <string, string> >(File.ReadAllText(_paramValueHistoryFilePath), JsonUtilities.DefaultSerializerOptions);
                        foreach (var v in localParameterValues)
                        {
                            _localParameterValues.AddOrUpdate(v.Key, key => v.Value, (key, oldValue) => oldValue);
                        }
                    }
                    finally
                    {
                        _mutex.ReleaseMutex();
                    }
                }
            });
        }
Exemplo n.º 9
0
        /// <summary>Stops watching the target URL.</summary>
        public void Stop()
        {
            _activated = false;

            if (_watchTimer == null)
            {
                return;
            }

            _watchTimer.Dispose();
            _watchTimer = null;

            _mutex.WaitOne();
            _mutex.ReleaseMutex();
        }
Exemplo n.º 10
0
 public static void LogLine(string line)
 {
     try
     {
         logmutex.WaitOne();
     }
     catch (System.Threading.AbandonedMutexException)
     {
     }
     try
     {
         System.IO.StreamWriter fstm = System.IO.File.AppendText("do5.txt");
         string build = "";
         try
         {
             System.Reflection.Assembly     asm = System.Reflection.Assembly.GetExecutingAssembly();
             System.Reflection.AssemblyName an  = asm.GetName();
             int bn = an.Version.Build;
             int rv = an.Version.Revision;
             build = "(do5." + bn.ToString() + "." + rv.ToString() + ") ";
         }
         catch
         {
         }
         fstm.WriteLine("[{0} {1}ms] {2}{3}", System.DateTime.Now.ToString(), System.DateTime.Now.Millisecond, build, line);
         fstm.Close();
     }
     finally
     {
         logmutex.ReleaseMutex();
     }
 }
Exemplo n.º 11
0
        public void CloseMutex()
        {
            bool isNew = false;
            Mutex closeMutex = new Mutex(true, mutexName, out isNew);

            if (isNew)
            {
                Console.WriteLine("CloseMutex create a new mutex:{0}", mutexName);
            }
            else
            {
                Console.WriteLine("CloseMutex can't create a new mutex:{0}", mutexName);
            }
            closeMutex.WaitOne();

            closeMutex.ReleaseMutex();

            Console.WriteLine("CloseMutex release mutex.");

            Thread.Sleep(5000);

            closeMutex.Close();

            Console.WriteLine("Close mutex");
        }
Exemplo n.º 12
0
 /// <summary>
 /// 添加一个消息
 /// </summary>
 public void PushData(Message ci)
 {
     mutex.WaitOne();
     if (BufferSize > 0 && BufferSize <= cmdq.Count)
     {
         Message c = cmdq.Peek() as Message;
         if (c != null && c.type == MsgQueue.msgtype_Send)
         {
             LostCount++;
             cmdq.Dequeue();
         }
     }
     cmdq.Enqueue(ci);
     evt.Set();
     mutex.ReleaseMutex();
 }
Exemplo n.º 13
0
        static void Main()
        {
            try
            {
                mutex = new Mutex(true, Settings.MutexGuid);
                if (mutex.WaitOne(TimeSpan.Zero, true))

                    try
                    {
                        RunProgram();
                    }
                    finally
                    {
                        mutex.ReleaseMutex();
                    }

                else
                    Platform.User32.PostMessage(

                        (IntPtr)Platform.PlatformApi.HWND_BROADCAST,
                        Platform.PlatformApi.WM_SHOWME,
                        IntPtr.Zero,
                        IntPtr.Zero);
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
            finally
            {
                if (mutex != null)
                    mutex.Dispose();
            }
        }
Exemplo n.º 14
0
    public static void Dump(string function, string trace, string content)
    {
        if (fs == null)
        {
            fs = new System.IO.FileStream(filename,
                                          System.IO.FileMode.Append,
                                          System.IO.FileAccess.Write,
                                          System.IO.FileShare.Read);
        }

        mt.WaitOne();

        string time = DateTime.Now.ToString("T");

        WriteLine("[" + time + "] Dump start: " + function);
        if (trace != null && trace != "")
        {
            WriteLine("### Trace: " + trace);
        }
        WriteLine(content);
        WriteLine("### Dump end (" + content.Length + " characters)");
        fs.Flush();

        Console.WriteLine(content);
        mt.ReleaseMutex();
    }
Exemplo n.º 15
0
        public static void Main()
        {
            Logger.Init();
            Logger.Info(@"GPSTran启动!");
            Logger.Warn(@"GPSTran启动!");
            Logger.Error(@"GPSTran启动!");
            Logger.Fatal(@"GPSTran启动!");
            Logger.Debug(@"GPSTran启动!");

            try
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                mutex = new System.Threading.Mutex(true, "OnlyRun");


                if (mutex.WaitOne(0, false))
                {
                    Splash = new SplashForm();
                    Application.Run(Splash);
                }
                else
                {
                    MessageBox.Show("程序已经在运行!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Application.Exit();
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.ToString());
            }
        }
Exemplo n.º 16
0
        public static void ShareMemory()
        {
            using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(MmfName, 10000))
            {
                Console.WriteLine("Process A started.");
                bool mutexCreated;
                var mutex = new Mutex(true, MmfMutex, out mutexCreated);

                using (MemoryMappedViewStream stream = mmf.CreateViewStream())
                {
                    var writer = new BinaryWriter(stream);
                    writer.Write('a');
                }
                mutex.ReleaseMutex();

                Console.WriteLine("Please start process B. Once it's done press ENTER.");
                Console.ReadLine();

                mutex.WaitOne();
                using (MemoryMappedViewStream stream = mmf.CreateViewStream())
                {
                    var reader = new BinaryReader(stream);
                    Console.WriteLine("Process A : {0}", reader.ReadChar());
                    Console.WriteLine("Process B : {0}", reader.ReadChar());
                    Console.ReadLine();
                }
                mutex.ReleaseMutex();
            }
        }
Exemplo n.º 17
0
        public AzureIndexInput(AzureDirectory azuredirectory, ICloudBlob blob)
            : base(blob.Name)
        {
            _name = blob.Uri.Segments[blob.Uri.Segments.Length - 1];

            _fileMutex = BlobMutexManager.GrabMutex(_name);
            _fileMutex.WaitOne();

            try
            {
                _azureDirectory = azuredirectory;
                _blobContainer = azuredirectory.BlobContainer;
                _blob = blob;

                string fileName = _name;
                StreamOutput fileStream = _azureDirectory.CreateCachedOutputAsStream(fileName);

                // get the blob
                _blob.DownloadToStream(fileStream);

                fileStream.Flush();
                Debug.WriteLine("GET {0} RETREIVED {1} bytes", _name, fileStream.Length);

                fileStream.Close();

                // and open it as an input
                _indexInput = CacheDirectory.openInput(fileName, IOContext.DEFAULT);
            }
            finally
            {
                _fileMutex.ReleaseMutex();
            }
        }
Exemplo n.º 18
0
        public int SendCommand(String command, int val = -1)
        {
            String retstr = "";

            sPortLock.WaitOne();
            try
            {
                if (val >= 0)
                {
                    sPort.WriteLine(":" + command + "," + val.ToString() + "*");
                }

                else
                {
                    sPort.WriteLine(":" + command + "*");
                }
                while (sPort.BytesToWrite > 0)
                {
                }
                retstr = sPort.ReadTo("*");
            }
            catch (Exception e)
            {
                LogMessage("SendCommand exception", e.ToString());
            }
            sPortLock.ReleaseMutex();
            return(Int32.Parse(retstr));
        }
Exemplo n.º 19
0
 public void ThreadStart()
 {
     Mutex mutex = new Mutex(false, "MyMutex");
     mutex.WaitOne();
     Console.WriteLine("Hello from Class2");
     //mutex.ReleaseMutex();
 }
Exemplo n.º 20
0
        static void Main()
        {
            Mutex mutex = new System.Threading.Mutex(false, "CWT");

            try
            {
                if (mutex.WaitOne(0, false))
                {
                    // Run the application
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new CWTNotify());
                }
                else
                {
                    MessageBox.Show("An instance of the application is already running.", "Information",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            finally
            {
                if (mutex != null)
                {
                    mutex.Close();
                    mutex = null;
                }
            }
        }
Exemplo n.º 21
0
        static void Main(string[] args)
        {
            using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("testmap", 10000))
            {
                bool mutexCreated;
                Mutex mutex = new Mutex(true, "testmapmutex", out mutexCreated);
                using (MemoryMappedViewStream stream = mmf.CreateViewStream())
                {
                    BinaryWriter writer = new BinaryWriter(stream);

                    Console.Write("Input number =>");
                    int num = int.Parse(Console.ReadLine());

                    writer.Write(num);
                }
                mutex.ReleaseMutex();

                Console.WriteLine("Start Process++ and press ENTER to continue.");
                Console.ReadLine();

                mutex.WaitOne();
                using (MemoryMappedViewStream stream = mmf.CreateViewStream())
                {
                    BinaryReader reader = new BinaryReader(stream);
                    Console.WriteLine("Process# says: {0}", reader.ReadInt32());
                    Console.WriteLine("Process++ says: {0}", reader.ReadInt32());
                }
                mutex.ReleaseMutex();
            }
        }
Exemplo n.º 22
0
        static void Main()
        {
            /// 20170720. AGL. Para evitar que se arranque mas de una instancia de la aplicacion.
            using (System.Threading.Mutex mutex = new System.Threading.Mutex(false, "Global\\" + appGuid))
            {
                if (!mutex.WaitOne(0, false))
                {
                    NLog.LogManager.GetLogger("HMI").Fatal("Instance already running...");
                    return;
                }

                Environment.CurrentDirectory = Path.GetDirectoryName(Application.ExecutablePath);
                try
                {
                    CultureInfo.DefaultThreadCurrentCulture   = new CultureInfo(Settings.Default.Idioma);
                    CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo(Settings.Default.Idioma);
                }
                catch (CultureNotFoundException exc)
                {
                    CultureInfo.DefaultThreadCurrentCulture   = Thread.CurrentThread.CurrentCulture;
                    CultureInfo.DefaultThreadCurrentUICulture = Thread.CurrentThread.CurrentCulture;
                }
                SetThreadPoolSize();
 #if (DEBUG)
                RunInDebugMode();
#else
                RunInReleaseMode();
#endif
                RestoreThreadPoolSize();
            }
        }
        //static System.Diagnostics.Process currentProcess = null;

        /// <summary>
        /// If it return false, exit program.  (ex. call if (Application.Current != null) { Application.Current.Shutdown(); })
        /// </summary>
        public static bool TryGetMutexOnTheBeginningOfApplicationConstructor()
        {
            // Refer to: http://stackoverflow.com/questions/229565/what-is-a-good-pattern-for-using-a-global-mutex-in-c
            var entryAssemblyFullName = Assembly.GetEntryAssembly().FullName;

            mutex = new System.Threading.Mutex(false, entryAssemblyFullName);
            // edited by Jeremy Wiebe to add example of setting up security for multi-user usage
            // edited by 'Marc' to work also on localized systems (don't use just "Everyone")
            var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
            var securitySettings  = new MutexSecurity();

            securitySettings.AddAccessRule(allowEveryoneRule);
            mutex.SetAccessControl(securitySettings);

            if (mutex.WaitOne(TimeSpan.Zero, false))
            {
                //currentProcess = System.Diagnostics.Process.GetCurrentProcess();
                //currentProcess.Exited += (sender, e) => { ReleaseMutex(); };
                return(true);
            }

            mutex.Close();
            mutex = null;
            return(false);
        }
Exemplo n.º 24
0
        static void Main()
        {
            Mutex mutex     = new System.Threading.Mutex(false, mutexName);
            bool  hasHandle = false;

            try {
                //多重起動の抑止
                try {
                    hasHandle = mutex.WaitOne(0, false);
                } catch (AbandonedMutexException) {
                    hasHandle = true;
                }

                if (hasHandle == false)
                {
                    return;
                }

                //フック開始
                StartHook();
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run();
            } catch (Exception e) {
                MessageBox.Show(e.Message);
            } finally {
                EndHook();

                if (hasHandle)
                {
                    mutex.ReleaseMutex();
                }
                mutex.Close();
            }
        }
Exemplo n.º 25
0
        private void Update(object state)
        {
            Mutex mtx = new Mutex(false, "RentMutex");
            bool isAppRunning = true;

            while (isAppRunning)
            {
                isAppRunning = !mtx.WaitOne(0, false);
            }

            //wait for the process to completely end
            Thread.Sleep(5000);

            string source = Program.Args[0];
            string destination = Program.Args[1];

            DirectoryInfo dir = new DirectoryInfo(source);

            foreach (FileInfo file in dir.GetFiles())
            {
                string dest = Path.Combine(destination, file.Name);
                FileInfo fi = new FileInfo(dest);
                if (fi.CreationTime != file.CreationTime) file.CopyTo(dest, true);
            }

            System.Diagnostics.Process.Start(Path.Combine(destination, "Rent.exe"));

            Application.Exit();
        }
Exemplo n.º 26
0
        static void Main()
        {
            using (Mutex mutex = new Mutex(false, "Global\\" + appGuid))
            {
                if (!mutex.WaitOne(0, false))
                {
                    MessageBox.Show("Ticket Soft Console Application ya está corriendo!");
                    return;
                }

                // Add the event handler for handling UI thread exceptions to the event.
                Application.ThreadException += new ThreadExceptionEventHandler(UIThreadException);

                // Set the unhandled exception mode to force all Windows Forms errors to go through
                // our handler.
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

                // Add the event handler for handling non-UI thread exceptions to the event.
                AppDomain.CurrentDomain.UnhandledException +=
                    new UnhandledExceptionEventHandler(UnhandledException);

                //Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new frmAdmin());
            }
        }
Exemplo n.º 27
0
        public void WriteMessage(String entry)
        {
            // in case we try and log in the event handlers. It's possible
            // multiple timers will pop at the same time
            bool requestInitialOwnership = true;
            bool mutexWasCreated;
            Mutex m = new Mutex(requestInitialOwnership, "PersonalPictureMgrMutex", out mutexWasCreated);
            if (!(requestInitialOwnership && mutexWasCreated))
            {
                m.WaitOne();
            }

            using (StreamWriter w = File.AppendText(m_logPath))
            {
                try
                {
                    DateTime curTime = DateTime.Now;
                    w.Write(curTime.ToString("s"));
                    w.Write(" " + m_methodName + " ");
                    w.WriteLine(entry);
                }
                catch (Exception)
                { }
                w.Close();
            }

            m.ReleaseMutex();
        }
Exemplo n.º 28
0
        // Create all necessary folders before saving the file
        public static void CreateFolderWhileNotExists(this string filePath)
        {
            string finalDirectoryPath = string.Empty;

            if (!string.IsNullOrEmpty(filePath))
                finalDirectoryPath = filePath.Substring(0, filePath.LastIndexOf(@"\"));

            if (!string.IsNullOrEmpty(finalDirectoryPath) && !Directory.Exists(finalDirectoryPath))
            {
                using (Mutex mutex = new Mutex(false, finalDirectoryPath.GetMutexName()))
                {
                    mutex.WaitOne();

                    try
                    {
                        System.IO.Directory.CreateDirectory(finalDirectoryPath);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                    finally
                    {
                        mutex.ReleaseMutex();
                    }
                }
            }
        }
Exemplo n.º 29
0
    public static void Main(string[] args)
    {
        try {
            if (!_Mutex.WaitOne(0, false))
            {
                _Mutex.Close();
                MessageBox.Show("Another instance is already running!", VodiWikiSaver.Product);
                return;
            }

            MenuItem item = new MenuItem()
            {
                Text = "&Exit"
            };
            item.Click += new System.EventHandler(Exit_Clicked);
            ContextMenu menu = new ContextMenu();
            menu.MenuItems.Add(item);

            _TrayIcon = new NotifyIcon()
            {
                Icon        = new Icon(Assembly.GetExecutingAssembly().GetManifestResourceStream(null, "VodiWikiSaver.ico")),
                Text        = "Vodi Wiki Saver " + Version,
                ContextMenu = menu,
                Visible     = true
            };

            _WebServer = new WebServer(HttpRequest_Recieved);
            _WebServer.Run();

            Application.Run();
        }
        catch (Exception e) {
            MessageBox.Show(e.ToString(), VodiWikiSaver.Product);
        }
    }
 public MutexWrapper(Mutex m)
 {
     this.m = m;
     try {
         m.WaitOne();
     } catch (AbandonedMutexException) { }
 }
Exemplo n.º 31
0
        static void Main()
        {
            Mutex _mutex = new System.Threading.Mutex(false, "SO2RInterface");

            try
            {
                if (_mutex.WaitOne(0, false))
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new Form());
                }
                else
                {
                    //MessageBox.Show("An instance of the application is already running.");
                }
            }
            finally
            {
                if (_mutex != null)
                {
                    _mutex.Close();
                }
            }
        }
Exemplo n.º 32
0
        public virtual void RemoveDirectoryAccess(string path, string user)
        {
            if (DirectoryExists(path) || FileExists(path))
            {
                using (var dirMutex = new System.Threading.Mutex(false, path.Replace('\\', '_')))
                {
                    dirMutex.WaitOne();
                    try
                    {
                        DirectorySecurity security = fileSystem.GetDirectoryAccessSecurity(path);

                        // RemoveAccessRuleAll ignores everything in the ACL but the username
                        var userACL = new FileSystemAccessRule(user, FileSystemRights.ListDirectory,
                                                               AccessControlType.Allow);
                        security.RemoveAccessRuleAll(userACL);

                        fileSystem.SetDirectoryAccessSecurity(path, security);
                    }
                    finally
                    {
                        dirMutex.ReleaseMutex();
                    }
                }
            }
        }
Exemplo n.º 33
0
        protected override void OnStartup(StartupEventArgs e)
        {
            var bnew = false;
            var appname = System.Windows.Forms.Application.ProductName;
            var mutex = new Mutex(true, appname, out bnew);
            if (bnew)
            {
                base.OnStartup(e);

                ConfigProfile.Current.ReadConfig();

                Channel.Init();

                CardPhoto.GetCardPhotos();

                Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
                Application.Current.MainWindow = new MainWindow();
                Application.Current.MainWindow.Show();
                mutex.WaitOne();
            }
            else
            {
                CustomDialog.Show("系统已运行!");
                Application.Current.Shutdown();
            }
        }
Exemplo n.º 34
0
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            var category =
                e.Args.Length >= 2 && e.Args[0] == "-c"
                    ? e.Args[1]
                    : null;

            if (singleton.WaitOne(TimeSpan.Zero, true))
            {
                singleton.ReleaseMutex();
                var mainWindow = new MainWindow(category);
                mainWindow.WindowState = WindowState.Normal;
                mainWindow.Show();
            }
            else
            {
                // send our Win32 message to make the currently running instance
                // jump on top of all the other windows
                NativeMethods.PostMessage(
                    (IntPtr)NativeMethods.HWND_BROADCAST,
                    NativeMethods.WM_SHOWME,
                    IntPtr.Zero,
                    IntPtr.Zero);
                this.Shutdown();
            }
        }
Exemplo n.º 35
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // We make sure that no other instances of that application is not running.
            bool mutexIsAvailable;
            Mutex m = null;
            try
            {
                m = new Mutex(true, "Singleton");
                // We are waiting for 1 ms.
                mutexIsAvailable = m.WaitOne(1, false);
            }
            catch (AbandonedMutexException)
            {
                // Do not worry about AbandonedMutexException.
                // Mutex only "protects" the application of it's copies.
                mutexIsAvailable = true;
            }
            if (!mutexIsAvailable) return;
            try
            {
                Application.Run(new Control());
            }
            finally
            {
                m?.ReleaseMutex();
            }
        }
Exemplo n.º 36
0
 static void Main()
 {
     mutex = new Mutex(true, "POS Memoku");
     if (mutex.WaitOne(0, false))
     {
         try
         {
             Application_Start();
             Application.EnableVisualStyles();
             Application.SetCompatibleTextRenderingDefault(false);
             LoginView loginView = new LoginView();
             ILoginController loginController = new LoginController(loginView);
             loginController.ShowLoginView();
             if (loginView.DialogResult.Equals(DialogResult.OK))
             {
                 loginView.Dispose();
                 InitializeComponent();
                 Application.Run(MainView.Instance(PosSettingRepository.Get().IsFullScreen));
             }
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message, string.Format("{0} - (1)",
                         Application.ProductName, Application.ProductVersion), MessageBoxButtons.OK, MessageBoxIcon.Warning);
         }
     }
 }
Exemplo n.º 37
0
        static void Main()
        {
            //new CrashLogTraceListener();

            using (Mutex mutex = new Mutex(false, MutexName))
            {
                if (mutex.WaitOne(1, true) == false)
                {
                    MessageBox.Show("Another instance of ConnectUO 2.0 Updater is running.  Please wait for that instance to close before running the Updater again.", "Already Running");
                    return;
                }

                for (Process[] processArray = Process.GetProcessesByName("ConnectUO.exe"); processArray.Length > 0; processArray = Process.GetProcessesByName("ConnectUO.exe"))
                {
                    Thread.Sleep(50);
                }

                _applicationInfo = new ApplicationInfo();

                Directory.SetCurrentDirectory(_applicationInfo.BaseDirectory);

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new frmUpdate());

                if (_status == UpdateStatus.Success)
                {
                    Process.Start(Path.Combine(_applicationInfo.BaseDirectory, "ConnectUO.exe"));
                }

                _applicationInfo.Process.Kill();
            }
        }
        private bool IsConsoleProcessRunning()
        {
            bool isConsoleServerRunning;

            #region Mutex avoid start twice
            Mutex mutex = new System.Threading.Mutex(false, "WindowsLivePhotoGalleryServer");
            try
            {
                //Allow only one server to run
                if (mutex.WaitOne(0, false))
                {
                    isConsoleServerRunning = false;
                }
                else
                {
                    isConsoleServerRunning = true;
                }
            }
            finally
            {
                if (mutex != null)
                {
                    mutex.Close();
                }
            }
            #endregion
            Logger.Trace("[Windows Live Photo Gallery | Console Process] IsConsoleServerRunning: " + isConsoleServerRunning);
            return(isConsoleServerRunning);
        }
Exemplo n.º 39
0
        static void Main()
        {
            using (Mutex mutex = new Mutex(false, @"Global\simpledlnaguilock")) {
            #if !DEBUG
            if (!mutex.WaitOne(0, false)) {
              using (var pipe = new NamedPipeClientStream(".", "simpledlnagui", PipeDirection.Out)) {
            try {
              pipe.Connect(10000);
              pipe.WriteByte(1);
            }
            catch (Exception) {
            }
            return;
              }
            }
            GC.Collect();
            #endif

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            using (var main = new FormMain()) {
              try {
            Application.Run(main);
              }
              catch (Exception ex) {
            log4net.LogManager.GetLogger(typeof(Program)).Fatal("Encountered fatal unhandled exception", ex);
            throw;
              }
            }
              }
        }
Exemplo n.º 40
0
    protected override void OnStartup(StartupEventArgs e)
    {
      fMutex = new Mutex(false, AppInfo.GetApplicationGuid());

      if(fMutex.WaitOne(0, false))
      {
        string settingsFilename;

        if(e.Args.Length > 0)
        {
          settingsFilename = e.Args[0];
        }
        else
        {
          settingsFilename = System.IO.Path.Combine(AppInfo.GetUserAppDataFolder(), AppInfo.GetApplicationName(), "Settings.xml");
        }

        AppSettings.Initialize(settingsFilename);

        Window wnd = new WindowMain();
        wnd.Show();

        base.OnStartup(e);
      }
      else
      {
        MessageBox.Show("An instance of " + AppInfo.GetApplicationName() + " is already running, only one instance is allowed at a time.");
        fMutex = null;
        this.Shutdown();
      }
    }
Exemplo n.º 41
0
        static void Main()
        {
            Util.Utils.ReleaseMemory();
            using (Mutex mutex = new Mutex(false, "Global\\" + "71981632-A427-497F-AB91-241CD227EC1F"))
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                if (!mutex.WaitOne(0, false))
                {
                    Process[] oldProcesses = Process.GetProcessesByName("Shadowsocks");
                    if (oldProcesses.Length > 0)
                    {
                        Process oldProcess = oldProcesses[0];
                    }
                    MessageBox.Show("Shadowsocks is already running.\n\nFind Shadowsocks icon in your notify tray.");
                    return;
                }
                Directory.SetCurrentDirectory(Application.StartupPath);
#if !DEBUG
                Logging.OpenLogFile();
#endif
                ShadowsocksController controller = new ShadowsocksController();

                MenuViewController viewController = new MenuViewController(controller);

                controller.Start();

                Application.Run();
            }
        }
Exemplo n.º 42
0
    public static void Main()
    {
        // 多重起動抑止処理
        System.Threading.Mutex mutex = new System.Threading.Mutex(false, "VRChatOpenBrowser");
        if (!mutex.WaitOne(0, false))
        {
            MessageBox.Show("すでに起動しています。2つ同時には起動できません。", "多重起動禁止");
            return;
        }

        // 設定をインスタンス化
        settings = new Settings("setting.yaml");

        // CheckUpdateが有効なら更新をチェックさせる
        if (settings.GetSettings() && settings.CheckUpdate)
        {
            OpenBrowser("https://github.com/YukiYukiVirtual/OpenBrowserServer/releases/");
        }
        else
        {
            WriteLog("Could not load the settings");
        }

        // サーバーを起動する
        StartServer();

        // Formをなんかする
        new VRChatOpenBrowser();
        Application.Run();
    }
Exemplo n.º 43
0
 private static void Main(string[] args)
 {
     Mutex mutex = new Mutex(true, AppDomain.CurrentDomain.BaseDirectory.Replace('\\', '_'));
     if (mutex.WaitOne(100))
     {
         Logger.Instance.WriteMessage("Notifier started.");
         SkypeNotifier.Instance.StartTimer();
         AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
         Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
         Application.Run(new Settings());
         SkypeNotifier.Instance.StopTimer();
         Logger.Instance.WriteMessage("Notifier halted.");
     }
     else
     {
         try
         {
             Process[] allProcesses = Process.GetProcessesByName("SkypeNotifier");
             if (allProcesses.Length > 0)
             {
                 Win32.SetForegroundWindow(allProcesses[0].MainWindowHandle);
             }
             return;
         }
         catch
         {
         }
     }
     mutex.ReleaseMutex();
 }
Exemplo n.º 44
0
        static void Main()
        {
            // Создаём новый мьютекс на время работы программы...
            using (Mutex Mtx = new Mutex(false, Properties.Resources.AppName))
            {
                // Пробуем занять и заблокировать, тем самым проверяя запущена ли ещё одна копия программы или нет...
                if (Mtx.WaitOne(0, false))
                {
                    // Включаем визуальные стили...
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);

                    // Получаем переданные параметры командной строки...
                    string[] CMDLineA = Environment.GetCommandLineArgs();

                    // Обрабатываем полученные параметры командной строки...
                    if (CMDLineA.Length > 2) { if (CMDLineA[1] == "/lang") { try { Thread.CurrentThread.CurrentUICulture = new CultureInfo(CMDLineA[2]); } catch { MessageBox.Show(Properties.Resources.AppUnsupportedLanguage, Properties.Resources.AppName, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } }

                    // Запускаем главную форму...
                    Application.Run(new FrmMainW());
                }
                else
                {
                    // Программа уже запущена. Выводим сообщение об этом...
                    MessageBox.Show(Properties.Resources.AppAlrLaunched, Properties.Resources.AppName, MessageBoxButtons.OK, MessageBoxIcon.Information);

                    // Завершаем работу приложения с кодом 16...
                    Environment.Exit(16);
                }
            }
        }
Exemplo n.º 45
0
        public static ReservedPort Reserve()
        {
            var port = 50000;
            while (port < ushort.MaxValue)
            {
                port++;
                
                if (!IsPortFree(port))
                {
                    continue;
                }

                bool createdNew;
                Mutex mutex = new Mutex(false, $@"Global\Knapcode.TorSharp.Tests.ReservedPort-{port}", out createdNew);
                lock (Lock)
                {
                    if (ReservedPorts.Contains(port))
                    {
                        continue;
                    }

                    var acquired = mutex.WaitOne(0, false);
                    if (acquired)
                    {
                        ReservedPorts.Add(port);
                        return new ReservedPort(port, mutex);
                    }
                }
            }

            return null;
        }
Exemplo n.º 46
0
		/// <summary>
		/// Implements the Next() method of the ISequenceNumber interface.
		/// The sequence number is read from a file, incremented, 
		/// then written back to the file
		/// </summary>
		/// <returns></returns>
		public int Next()
		{
			FileInfo serialFile = new FileInfo(this.path);
			string name = serialFile.FullName.Replace('\\', '/');
			using (Mutex mutex = new Mutex(true, name))
			{
				mutex.WaitOne();
				int serial = 1;
				if (serialFile.Exists)
				{
					using (StreamReader sr = new StreamReader(serialFile.FullName))
					{
						string text = sr.ReadToEnd();
						serial = Convert.ToInt32(text);
						++serial;
					}
				}

				using (StreamWriter sr = new StreamWriter(serialFile.FullName))
				{
					sr.Write(serial.ToString());
				}
			
				return serial;
			}
		}
Exemplo n.º 47
0
        private static void Main()
        { 
#if DEBUG
            //EFlogger.EntityFramework6.EFloggerFor6.Initialize();  
#endif
            Mutex runOnce = null;
            try
            {
                runOnce = new Mutex(true, "Events_V2_Application_Mutex");
                if (runOnce.WaitOne(TimeSpan.Zero))
                {
                    Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                    Application.ThreadException += ExceptionHandler.ThreadExceptionHandler;
                    AppDomain.CurrentDomain.UnhandledException += ExceptionHandler.UnhandledExceptionHandler;
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new EventsMainForm());
                }
                else
                {
                    InfoForm info = new InfoForm()
                    {
                        InfoMessage = {Text = @"Приложение уже запущено!"}
                    };
                    info.ShowDialog();
                }
            }
            finally
            {
                if (null != runOnce)
                    runOnce.Close();
            }
        }
Exemplo n.º 48
0
        static void Main()
        {
            Util.Utils.ReleaseMemory();
            using (Mutex mutex = new Mutex(false, "Global\\ShadowsocksR_" + Application.StartupPath.GetHashCode()))
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                if (!mutex.WaitOne(0, false))
                {
                    MessageBox.Show(I18N.GetString("Find Shadowsocks icon in your notify tray.") + "\n" +
                        I18N.GetString("If you want to start multiple Shadowsocks, make a copy in another directory."),
                        I18N.GetString("ShadowsocksR is already running."));
                    return;
                }
                Directory.SetCurrentDirectory(Application.StartupPath);
            //#if !DEBUG
                Logging.OpenLogFile();
            //#endif
                ShadowsocksController controller = new ShadowsocksController();

                MenuViewController viewController = new MenuViewController(controller);

                controller.Start();

                Application.Run();
            }
        }
Exemplo n.º 49
0
    public static Mutex AcquireMutex(NodeUri nodeUri, TimeSpan timeout)
    {
      Debug.Print("Acquire Mutex for Node URI '{0}'", nodeUri);
      var mutexName = GetMutexName(nodeUri);

      Debug.Print("Acquire Mutex name: '{0}'", mutexName);
      bool mutexCreated;
      var mutex = new Mutex(false, mutexName, out mutexCreated);

      Debug.Print("Mutex instance resolved - instance created: {0}", mutexCreated);
      try
      {
        Debug.Print("Try to aquire lock on mutex using timeout {0}", timeout);
        if (!mutex.WaitOne(timeout))
        {
          throw new TimeoutException(string.Format("Cannot acquire Mutex for URI '{0}' - there is another Node already exists for the same URI", nodeUri));
        }

        Debug.Print("Mutex successfully acquired!");
        return mutex;
      }
      catch (AbandonedMutexException abandonedMutexException)
      {
        Debug.Print("Mutex Abandoned Exception: {0}", abandonedMutexException.Message);

        mutex.ReleaseMutex();
        return AcquireMutex(nodeUri, timeout);
      }
    }
Exemplo n.º 50
0
 public MutexLock(string mutexname)
 {
     m = new Mutex(false, mutexname);
     if(m.WaitOne(0, false) == false) {
         throw new MutexAlreadyExists();
     }
 }
Exemplo n.º 51
0
        public static void Main()
        {
            var taken = false;
              var mutex = new Mutex(false, "qwiki.webdav.chrome");
              LocalServer server = null;

              try {
            if (!mutex.WaitOne(0)) return;
            taken = true;

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            server = new LocalServer();
            server.Start();

            Application.Run();
              }
              finally {
            server?.Disconnect();
            server?.Dispose();
            if (taken) {
              mutex.Close();
            }
              }
        }
Exemplo n.º 52
0
        private static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine(
                    "The update system have been modified and is not compatible with your meter version. Download the new version directly from the website.");
                Console.ReadLine();
                return;
            }

            bool aIsNewInstance, isUpdating;
            var _unique = new Mutex(true, "ShinraMeter", out aIsNewInstance);
            if (!aIsNewInstance)
            {
                while (!_unique.WaitOne(1000))
                {
                    Console.WriteLine("Sleep");
                }
            }
            Thread.Sleep(1000);
            var uniqueUpdating = new Mutex(true, "ShinraMeterUpdating", out isUpdating);

            UpdateManager.DestroyRelease();
            CountError(0);
            var source = Directory.GetDirectories(UpdateManager.ExecutableDirectory + @"\..\release\")[0];
            UpdateManager.Copy(source, UpdateManager.ExecutableDirectory + @"\..\..\");
            Console.WriteLine("New version installed");
            Process.Start("explorer.exe", "https://github.com/neowutran/ShinraMeter/wiki/Patch-note");
            Process.Start(UpdateManager.ExecutableDirectory + @"\..\..\ShinraMeter.exe");
            Environment.Exit(0);
        }
Exemplo n.º 53
0
        public override string GetVideoUrl(VideoInfo video)
        {
            string playURL = "";

            if (!FeedSync.WaitOne(60000))
            {
                Log.Error("ABCiViewUtil2: Wait for FeedSync Thread failed");
            }
            else
            {
                ProgramData programData;

                if (ProgramDictionary.TryGetValue(video.Other.ToString(), out programData))
                {
                    playURL = programData.playURL;
                }
                else
                {
                    //Try and get the Feed Again as it may be out of date
                    Log.Debug("ABCiView2Util: Cannot find episode in TV Feed. Refresh");

                    new System.Threading.Thread(FeedSyncWorker)
                    {
                        IsBackground = true, Name = "TVFeedDownload"
                    }.Start(iViewTVFeedURL);
                    if (!FeedSync.WaitOne(60000))
                    {
                        if (ProgramDictionary.TryGetValue(video.Other.ToString(), out programData))
                        {
                            playURL = programData.playURL;
                        }
                        else
                        {
                            Log.Debug("ABCiView2Util: Cannot find episode in TV Feed after refresh");
                        }
                    }
                    else
                    {
                        Log.Error("ABCiViewUtil2: Wait for FeedSync Thread failed");
                    }
                }
                FeedSync.ReleaseMutex();
            }

            return(playURL);
        }
Exemplo n.º 54
0
        private string GetSqlCeDbFileName(string baseGroupName, string subName, bool createDatabaseIfItDoesNotExist = true)
        {
            string fn = Path.Combine(_BasePath, baseGroupName);

            if (Directory.Exists(fn) == false)
            {
                Directory.CreateDirectory(fn);
            }

            if (string.IsNullOrEmpty(subName))
            {
                fn = Path.Combine(fn, "_Main.Group.sdf");
            }
            else
            {
                fn = Path.Combine(fn, subName + ".sdf");
            }

            if (File.Exists(fn) == false)
            {
                //string[] names = this.GetType().Assembly.GetManifestResourceNames();
                if (createDatabaseIfItDoesNotExist == false)
                {
                    return(null);
                }

                // Here I need to use a mutex to prevent duplicate creating of the file... this leads to sharing violations...
                string mutexName = _FileCreateAppId.ToString("D", System.Globalization.CultureInfo.InvariantCulture) + baseGroupName.ToLowerInvariant();
                using (var m = new System.Threading.Mutex(false, mutexName))
                {
                    m.WaitOne();
                    try
                    {
                        if (File.Exists(fn) == false) // prüfe hier nochmals, da ich nur hier den Mutex besitze!
                        {
                            using (var db =
                                       typeof(AnswersDataEntities).Assembly.GetManifestResourceStream(
                                           "CommunityBridge2.WebServiceAnswers.AnswersData.sdf"))
                            {
                                byte[] data = new byte[db.Length];
                                db.Read(data, 0, data.Length);
                                string fn2 = fn + "_tmp";
                                using (var f = File.Create(fn2))
                                {
                                    f.Write(data, 0, data.Length);
                                }
                                File.Move(fn2, fn);
                            }
                        }
                    }
                    finally
                    {
                        m.ReleaseMutex();
                    }
                }
            }
            return(fn);
        }
Exemplo n.º 55
0
        static void Main(string[] args)
        {
#if !DEBUG
            Application.ThreadException += new
                                           ThreadExceptionEventHandler(Application_ThreadException);
            // UnhandledExceptionイベント・ハンドラを登録する
            Thread.GetDomain().UnhandledException += new
                                                     UnhandledExceptionEventHandler(Application_UnhandledException);
#if ADMIN
            string mutexName = "MisakiEQ(Admin Mode)";
#else
            string mutexName = "MisakiEQ";
#endif
            //Mutexオブジェクトを作成する
            mutex = new System.Threading.Mutex(false, mutexName);


            try
            {
                //ミューテックスの所有権を要求する
                hasHandle = mutex.WaitOne(0, false);
            }
            //.NET Framework 2.0以降の場合
            catch (System.Threading.AbandonedMutexException)
            {
                //別のアプリケーションがミューテックスを解放しないで終了した時
                hasHandle = true;
            }
            //ミューテックスを得られたか調べる
            if (hasHandle == false)
            {
                //得られなかった場合は、すでに起動していると判断して終了
                MessageBox.Show("MisakiEQは多重起動できません。\nもし表示されない場合はタスクトレイをチェックしてください。", "MisakiEQ", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
#endif
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            for (int i = 0; args.Count() > i; i++)
            {
                if (args[i].StartsWith("ErrorFlg="))
                {
                    ErrorCount = int.Parse(args[i].Remove(0, 9));
                }
            }

            MainForm = new MainForm();
            Application.Run(MainForm);
#if !DEBUG
            if (hasHandle)
            {
                //ミューテックスを解放する
                mutex.ReleaseMutex();
            }
#endif
        }
Exemplo n.º 56
0
        public String ReadLine(MutexAction action = MutexAction.NONE)
        {
            String cad;

            if (action == MutexAction.ADQUIRE || action == MutexAction.ATOMIC)
            {
                mutex.WaitOne();
            }

            cad = this.input.ReadLine();

            if (action == MutexAction.RELAX || action == MutexAction.ATOMIC)
            {
                mutex.ReleaseMutex();
            }

            return(cad);
        }
Exemplo n.º 57
0
        static bool _AppIsRunning(string appName)
        {
            string _Name = appName.Replace(System.IO.Path.DirectorySeparatorChar, '_'); //

            System.Threading.Mutex _mutex = new System.Threading.Mutex(false, _Name);
            bool _isRunning = !_mutex.WaitOne(0, false);

            return(_isRunning);
        }
Exemplo n.º 58
0
        private void WriteToFile()
        {
            using System.Threading.Mutex mutex = new System.Threading.Mutex(false, "OS-Übergreifender Mutex");
            mutex.WaitOne();

            File.AppendAllText(_fileName, $"{nameof(Mutex)}: {DateTime.Now:hh:mm:ss:ffff} {Environment.NewLine}");

            mutex.ReleaseMutex();
        }
Exemplo n.º 59
0
 /// <summary>
 /// Constructs a new PipeClient
 /// </summary>
 /// <param name="name">The name of the pipe to use</param>
 public PipeServer(string name)
 {
     _name  = name;
     _mutex = new Mutex(false, name);
     if (!_mutex.WaitOne(5000)) //this should wait for another server to finish cleanup (if one is cleaning up)
     {
         throw new Exception("The named pipe is already in use");
     }
 }
Exemplo n.º 60
-1
        static void Main()
        {
            Util.Utils.ReleaseMemory();
            using (Mutex mutex = new Mutex(false, "Global\\" + "71981632-A427-497F-AB91-241CD227EC1F"))
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                if (!mutex.WaitOne(0, false))
                {
                    Process[] oldProcesses = Process.GetProcessesByName("Shadowsocks");
                    if (oldProcesses.Length > 0)
                    {
                        Process oldProcess = oldProcesses[0];
                    }
                    MessageBox.Show("已经存在运行的I-WALL,请检查系统托盘。");
                    return;
                }
                Directory.SetCurrentDirectory(Application.StartupPath);
            #if !DEBUG
                Logging.OpenLogFile();
            #endif
                ShadowsocksController controller = new ShadowsocksController();

                MenuViewController viewController = new MenuViewController(controller);

                controller.Start();
               /* if (System.IO.File.Exists(@"C:\test.txt"))
                          System.IO.File.Delete(@"C:\test.txt");*/
                Application.Run();
            }
        }