【问题标题】:When use .net Mutex to ensure single instance, is that possible update first instance when launch second instance当使用 .net Mutex 来确保单个实例时,是否可以在启动第二个实例时更新第一个实例
【发布时间】:2018-11-26 08:12:22
【问题描述】:

我有一个 winform 应用程序。用于阻止创建多个实例的 Mutex 类。

static class Program
{

    public static string IDFromAnotherApp = "default";
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        if (args.Length > 0)
            IDFromAnotherApp = args[0];

        bool successAquisition;
        Mutex programMutex = new Mutex(true,
            AppDomain.CurrentDomain.SetupInformation.ApplicationName,
            out successAquisition);

        if (successAquisition)
        {
            Application.Run(new Form1());
            programMutex.ReleaseMutex();
            GC.KeepAlive(programMutex);

        }
        else
        {
            IDFromAnotherApp = "another";
            MessageBox.Show("already open");

        } 

    }
}

Form1 代码

    public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
        DisplayId();   
    }

    public void DisplayId()
    {
        label1.Text = Program.IDFromAnotherApp;
    }
}

现在当用户点击带参数的APP时,Form1 label1控件将呈现该值,但如果另一个用户再次点击APP,弹出窗口会说“已经打开”

我想做得更好,不是弹出窗口,当另一个用户点击带有参数的APP时,已经打开的Form1可以更新它的label1的文本吗?这甚至可能吗?

【问题讨论】:

    标签: c# .net singleton mutex


    【解决方案1】:

    你可以使用任何一种数字技术

    1. 命名管道
    2. Windows 消息
    3. Windows 套接字
    4. WCF
    5. 还有更多...

    我建议使用 NamedPipes 或者可能是 Windows 消息

    至于具体如何做到这一点,互联网上有很多例子,一个很好的练习供你研究。如果您对任何特定技术有疑问,欢迎就您遇到的具体问题提出其他问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      相关资源
      最近更新 更多