xiaokang088

mutex可以 用来控制应用程序只启动一次,但是要注意mutex不能被回收,否则就无法发挥作用了。

例如:

   bool ret;
            using (System.Threading.Mutex  mutex = new System.Threading.Mutex(true, "WpfMuerterrrterterttex", out ret))
            {
                if (!ret)
                    Environment.Exit(0);
            }

这样子写,mutex会被回收,如下的方法是正确的:

using System;
using System.Windows;

namespace WpfApplication1
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        System.Threading.Mutex mutex;

        public App()
        {
            this.Startup += new StartupEventHandler(App_Startup);
        }

        void App_Startup(object sender, StartupEventArgs e)
        {
            bool ret;
            mutex = new System.Threading.Mutex(true, "WpfMuerterrrterterttex", out ret);

            if (!ret)
                Environment.Exit(0);
        }
    }
}

之前通过查找process的方法来控制应用程序启动,如下,发现这个方法有bug:在多用户登录后,只有一个用户可以正常启动程序,也就是说,进程是跨用户的。

            int processCount = Process.GetProcessesByName("windowWPF").Where(o => o.Id != Process.GetCurrentProcess().Id).Count();
            if (processCount > 1)
                Environment.Exit(0);

关于mutex,貌似存在性能问题,希望聆听高见,如何处理此类问题。

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-11-07
  • 2022-12-23
  • 2021-07-26
  • 2021-10-16
  • 2021-06-22
  • 2022-12-23
猜你喜欢
  • 2021-06-09
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案