zoukankan      html  css  js  c++  java
  • 让程序只启动一次 Mutex

    有时在开发程序的时候, 有时需要只能同时运行一个实例.
    Mutex 类, 称为互拆体, 是一个同步基元, 它只向一个线程授予对共享资源的独占访问权。
    当两个或更多线程需要同时访问一个共享资源时,系统需要使用同步机制来确保一次只有一个线程使用该资源。
    如果一个线程获取了互斥体,则要获取该互斥体的第二个线程将被挂起,直到第一个线程释放该互斥体。

    下面演示 Mutex 类来保证应用程序只有唯一实例

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Windows.Forms;

    namespace 让程序只启动一次
    {
        
    static class Program
        {
            
    /// <summary>
            
    /// 应用程序的主入口点。
            
    /// </summary>
            [STAThread]
            
    static void Main()
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(
    false);

                
    bool bCreate;
                System.Threading.Mutex mutex 
    = new System.Threading.Mutex(false"SINGILE_INSTANCE_MUTEX"out bCreate);

                
    if (bCreate)
                {
                    Application.Run(
    new Form1());
                }
                
    else
                {
                    MessageBox.Show(
    "程序已经启动");
                    Application.Exit();
                }
            }
        }
    }
  • 相关阅读:
    mysqldump
    设计模式
    设计模式
    设计模式
    设计模式
    PHP 调试
    PHP 调试
    Windows 下手工搭建 LNMP 环境
    设计模式
    设计模式
  • 原文地址:https://www.cnblogs.com/LinFx/p/2123690.html
Copyright © 2011-2022 走看看