• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# Threading.Mutex类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.Threading.Mutex的典型用法代码示例。如果您正苦于以下问题:C# Mutex类的具体用法?C# Mutex怎么用?C# Mutex使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



Mutex类属于System.Threading命名空间,在下文中一共展示了Mutex类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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


示例16: Reserve

        public static ReservedPort Reserve()
        {
            var port = 50000;
            while (port < ushort.MaxValue)
            {
                port++;
                
                if (!IsPortFree(port))
                {
                    continue;
                }

                bool createdNew;
                Mutex mutex = new Mutex(false, [email protected]"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;
        }
开发者ID:JSkimming,项目名称:TorSharp,代码行数:32,代码来源:ReservedPort.cs


示例17: Main

 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();
 }
开发者ID:vhytyk,项目名称:skype-notifier,代码行数:30,代码来源:Program.cs


示例18: ChannelsViewForm

        private Mutex mutex = null; // синхронизатор

        #endregion Fields

        #region Constructors

        public ChannelsViewForm(Application _app)
        {
            app = _app;
            InitializeComponent();

            mutex = new Mutex();
        }
开发者ID:slawer,项目名称:devicemanager,代码行数:13,代码来源:ChannelsViewForm.cs


示例19: Main

        static void Main(string[] args)
        {
            Process instance = RunningInstance();
            if (instance != null)
            {
                HandleRunningInstance(instance);
                return;
            }
            else
            {
                bool canCreateThread;
                Mutex mutex = new Mutex(true, Application.UserAppDataPath.Replace("\\", "_"), out canCreateThread);

                if (!canCreateThread)
                {
                    MessageBox.Show("应用程序已在运行中!", "消息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                if (args.Length > 0)
                {
                    try
                    {
                        //string[] strTemp = args[0].Split('@');
                        //Common.globalAppVNo = strTemp[0];
                        //Common.globalAppMD5No = strTemp[1];
                        Common.globalUpdateList = args[0];
                    }
                    catch { }
                }
                Application.Run(new UpdateForm());
            }
        }
开发者ID:wgang10,项目名称:XTHospatal,代码行数:34,代码来源:Program.cs


示例20: AcquireMutex

    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);
      }
    }
开发者ID:alexrster,项目名称:QX.NodeParty,代码行数:29,代码来源:Node.cs



注:本文中的System.Threading.Mutex类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Threading.NativeOverlapped类代码示例发布时间:2022-05-26
下一篇:
C# Threading.ManualResetEventSlim类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap