當前位置: 首頁>>代碼示例>>C#>>正文


C# Threading.Mutex類代碼示例

本文整理匯總了C#中System.Threading.Mutex的典型用法代碼示例。如果您正苦於以下問題:C# Mutex類的具體用法?C# Mutex怎麽用?C# Mutex使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Mutex類屬於System.Threading命名空間,在下文中一共展示了Mutex類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: OnStartup

 protected override void OnStartup(StartupEventArgs e)
 {
     AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
     App.Current.DispatcherUnhandledException += (s, ex) => MessageBox.Show(ex.Exception.ToString());
     // Check for running instances of Patchy and kill them
     bool isInitialInstance;
     Singleton = new Mutex(true, "Patchy:" + SingletonGuid, out isInitialInstance);
     if (!isInitialInstance)
         KillCurrentInstance();
     Singleton.Close();
     // Check for permissions
     if (!Patchy.UacHelper.IsProcessElevated && !Debugger.IsAttached)
     {
         var info = new ProcessStartInfo(Assembly.GetEntryAssembly().Location);
         info.Verb = "runas";
         Process.Start(info);
         Application.Current.Shutdown();
         return;
     }
     // Check for .NET 4.0
     var value = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full", "Install", null);
     if (value == null)
     {
         var result = MessageBox.Show("You must install .NET 4.0 to run Patchy. Would you like to do so now?",
             "Error", MessageBoxButton.YesNo, MessageBoxImage.Error);
         if (result == MessageBoxResult.Yes)
             Process.Start("http://www.microsoft.com/en-us/download/details.aspx?id=17851");
         Application.Current.Shutdown();
         return;
     }
 }
開發者ID:naiduv,項目名稱:Patchy,代碼行數:31,代碼來源:App.xaml.cs

示例2: Main

        static void Main()
        {
            mutex = new Mutex(true, Process.GetCurrentProcess().ProcessName, out created);
            if (created)
            {
                //Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                //Application.ThreadException += Application_ThreadException;
                //AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

                // As all first run initialization is done in the main project,
                // we need to make sure the user does not start a different knot first.
                if (CfgFile.Get("FirstRun") != "0")
                {
                    try
                    {
                        ProcessStartInfo process = new ProcessStartInfo(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\FreemiumUtilities.exe");
                        Process.Start(process);
                    }
                    catch (Exception)
                    {
                    }

                    Application.Exit();
                    return;
                }

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new FormMain());
            }
        }
開發者ID:nullkuhl,項目名稱:fsu-dev,代碼行數:31,代碼來源:Program.cs

示例3: Main

        static void Main()
        {
            bool createdMutex;

            var updateCheck = new UpdateCheck();
            updateCheck.CheckUri = "http://minecraft.etherealwake.com/updates.xml";
            updateCheck.Start();

            using (var mutex = new Mutex(true, mutexName, out createdMutex)) {
                if (createdMutex) {
                    // Created the mutex, so we are the first instance
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    var mainform = new MainForm();
                    Application.Run(mainform);
                    GC.KeepAlive(mutex);
                } else {
                    // Not the first instance, so send a signal to wake up the other
                    try {
                        var message = NativeMethods.RegisterWindowMessage(mutexName);
                        if (message != 0) {
                            NativeMethods.PostMessage(NativeMethods.HWND_BROADCAST,
                                message, IntPtr.Zero, IntPtr.Zero);
                        }
                    } catch {
                        // We really don't care, we're quitting anyway
                    }
                }
            }
        }
開發者ID:EtherealWake,項目名稱:test-intel,代碼行數:30,代碼來源:Program.cs

示例4: SensorForm

 public SensorForm(MainForm mainForm)
 {
     _mf = mainForm;
     dispMutex = new Mutex();
     InitializeComponent();
     waveBoxV.Initialize(10,10,-10);
     _lineName.Add((int)DataType.Heading, "艏向角");
     _lineName.Add((int)DataType.Pitch, "縱傾");
     _lineName.Add((int)DataType.Roll, "橫搖");
     _lineName.Add((int)DataType.Pressure, "壓強");
     _lineName.Add((int)DataType.Temperature, "溫度"); 
     _lineName.Add((int)DataType.Speed, "航速");
     _lineName.Add((int)DataType.Depth, "拖體深度");
     _lineName.Add((int)DataType.Altitude, "底深");
     MonoColors.Add(Color.Aqua);
     MonoColors.Add(Color.Blue);
     MonoColors.Add(Color.BlueViolet);
     MonoColors.Add(Color.Brown);
     MonoColors.Add(Color.BurlyWood);
     MonoColors.Add(Color.CadetBlue);
     MonoColors.Add(Color.Chartreuse);
     MonoColors.Add(Color.Chocolate);
     MonoColors.Add(Color.CornflowerBlue);
     MonoColors.Add(Color.Crimson);
     MonoColors.Add(Color.DeepPink);
     waveBoxV.AddLine(_lineName[(int)DataType.Heading], MonoColors[0]);
     waveBoxV.AddLine(_lineName[(int)DataType.Pitch], MonoColors[1]);
     waveBoxV.AddLine(_lineName[(int)DataType.Roll], MonoColors[2]);
     option.bShowHeading = true;
     option.bShowPitch = true;
     option.bShowRoll = true;
 }
開發者ID:BoonieBear,項目名稱:BSS,代碼行數:32,代碼來源:SensorForm.cs

示例5: Main

        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            AppPath = (Application.StartupPath.ToLower());
            AppPath = AppPath.Replace(@"\bin\debug", @"\").Replace(@"\bin\release", @"\");
            AppPath = AppPath.Replace(@"\bin\x86\debug", @"\").Replace(@"\bin\x86\release", @"\");

            AppPath = AppPath.Replace(@"\\", @"\");

            if (!AppPath.EndsWith(@"\"))
                AppPath += @"\";

            if (args.Length > 0)
            {
                ProgramName = args[0];
                AppDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\" + ProgramName +
                              @"\";
                bool firstInstance;
                var mutex = new Mutex(false, "iSpyMonitor", out firstInstance);
                if (firstInstance)
                    Application.Run(new Monitor());
                mutex.Close();
                mutex.Dispose();
            }
        }
開發者ID:WesleyYep,項目名稱:ispyconnect,代碼行數:27,代碼來源:Program.cs

示例6: fmMain_Load

        private void fmMain_Load(object sender, EventArgs e)
        {
            bool r;
            AppMutex = new Mutex(true, "AndonSys.AppHelper", out r);
            if (!r)
            {
                MessageBox.Show("係統已運行!",this.Text);
                Close();
                return;
            }
            
            CONFIG.Load();

            log = new Log(Application.StartupPath, "AppHelper", Log.DEBUG_LEVEL);

            log.Debug("係統運行");
           
            gdApp.AutoGenerateColumns = false;
           
            LoadApp();
            
            tbApp.Show();

            timer.Enabled = true;
        }
開發者ID:puyd,項目名稱:AndonSys.Test,代碼行數:25,代碼來源:fmAppHelper.cs

示例7: MutexLock

 /// <summary> Locks the provided mutex or throws TimeoutException </summary>
 /// <exception cref="System.TimeoutException"> Raises System.TimeoutException if mutex was not obtained. </exception>
 public MutexLock(int timeout, Mutex mutex)
 {
     _wasNew = false;
     _mutex = Check.NotNull(mutex);
     _disposeMutex = false;
     Lock(timeout, ref _wasAbandonded);
 }
開發者ID:hivie7510,項目名稱:csharptest-net,代碼行數:9,代碼來源:MutexLock.cs

示例8: Main

        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);
                }
            }
        }
開發者ID:xvitaly,項目名稱:srcrepair,代碼行數:31,代碼來源:Program.cs

示例9: Main

        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();
            }
        }
開發者ID:Winsor,項目名稱:ITInfra,代碼行數:33,代碼來源:Program.cs

示例10: Main

        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            //DevExpress.Skins.SkinManager.EnableFormSkins();
            //UserLookAndFeel.Default.SetSkinStyle("Office 2013");
            CurrentUser=new User();
            // Giá trị luận lý cho biết ứng dụng này
            // có quyền sở hữu Mutex hay không.
            bool ownmutex;

            // Tạo và lấy quyền sở hữu một Mutex có tên là Icon;
            using (var mutex = new Mutex(true, "Icon", out ownmutex))
            {
                // Nếu ứng dụng sở hữu Mutex, nó có thể tiếp tục thực thi;
                // nếu không, ứng dụng sẽ thoát.
                if (ownmutex)
                {
                    Application.Run(new FormLogin());
                    //giai phong Mutex;
                    mutex.ReleaseMutex();
                }
                else
                    Application.Exit();
            }  
        }
開發者ID:cuongpv88,項目名稱:work,代碼行數:26,代碼來源:Program.cs

示例11: OnStartup

        protected override void OnStartup(StartupEventArgs e)
        {
            // store mutex result
            bool createdNew;

            // allow multiple users to run it, but only one per user
            var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
            var securitySettings = new MutexSecurity();
            securitySettings.AddAccessRule(allowEveryoneRule);

            // create mutex
            _instanceMutex = new Mutex(true, @"Global\MercurialForge_Mastery", out createdNew, securitySettings);

            // check if conflict
            if (!createdNew)
            {
                MessageBox.Show("Instance of Mastery is already running");
                _instanceMutex = null;
                Application.Current.Shutdown();
                return;
            }

            base.OnStartup(e);
            MainWindow window = new MainWindow();
            MainWindowViewModel viewModel = new MainWindowViewModel(window);
            window.DataContext = viewModel;
            window.Show();
        }
開發者ID:MercurialForge,項目名稱:Mastery,代碼行數:28,代碼來源:App.xaml.cs

示例12: Main

 static void Main(string[] args)
 {
     bool can_execute = true;
     try
     {
         mutex = new System.Threading.Mutex(false, "MONITORMANAGER", out can_execute);
     }
     catch (Exception ex)
     {
         _logService.Error("ExistCatch:獲取Mutex時出現異常:" + ex.ToString());
     }
     if (can_execute)
     {
         Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
         Application.ThreadException += Application_ThreadException;
         AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);
         if (args == null || args.Length == 0 || args[0].ToLower() == "true")
         {
             Application.Run(new MonitorMain(true));
         }
         else
         {
             Application.Run(new MonitorMain(false));
         }
     }
     else
     {
         _logService.Info("MONITORMANAGER already running!");
         Debug.WriteLine("MONITORMANAGER already running!");
     }
 }
開發者ID:hardborn,項目名稱:MonitorManager,代碼行數:33,代碼來源:Program.cs

示例13: Main

        static void Main()
        {
            bool createdNew;    //是否是第一次開啟程序
            Mutex mutex = new Mutex(false, "Single", out createdNew);//實例化一個進程互斥變量,標記名稱Single
            if (!createdNew)                                        //如果多次開啟了進程
            {
            Process currentProcess = Process.GetCurrentProcess();//獲取當前進程
            foreach (Process process in Process.GetProcessesByName(currentProcess.ProcessName))
            {
            //通過進程ID和程序路徑來獲取一個已經開啟的進程
            if ((process.Id != currentProcess.Id) &&
            (Assembly.GetExecutingAssembly().Location == process.MainModule.FileName))
            {
            //獲取已經開啟的進程的主窗體句柄
            IntPtr mainFormHandle = process.MainWindowHandle;
            if (mainFormHandle != IntPtr.Zero)
            {
                ShowWindowAsync(mainFormHandle, 1);         //顯示已經開啟的進程窗口
                SetForegroundWindow(mainFormHandle);        //將已經開啟的進程窗口移動到窗體的最前端
            }
            }
            }
            MessageBox.Show("進程已經開啟");
            return;
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new FormSingleProcess());
        }
開發者ID:dalinhuang,項目名稱:wdeqawes-efrwserd-rgtedrtf,代碼行數:30,代碼來源:Program.cs

示例14: Main

        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();
            }
        }
開發者ID:xie3507,項目名稱:shadowsocks-csharp,代碼行數:31,代碼來源:Program.cs

示例15: Main

        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            var c = Process.GetCurrentProcess();

            bool instance;
            var mutex = new Mutex(true, c.ProcessName + Application.ProductName, out instance);

            if (!instance)
            {
                // Search for instances of this application
                var first = false;

                foreach (var p in Process.GetProcessesByName(c.ProcessName).Where(p => p.Id != c.Id))
                    if (!first)
                    {
                        first = true;
                        ShowWindow(p.MainWindowHandle, 5);
                        SetForegroundWindow(p.MainWindowHandle);
                    }
                    else
                        p.Kill();
            }
            else
            {
                Application.Run(new FormMain());
                GC.KeepAlive(mutex);
            }
        }
開發者ID:dbbotkin,項目名稱:PrimeComm,代碼行數:30,代碼來源:Program.cs


注:本文中的System.Threading.Mutex類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。