WebEnh

.net7 mvc jquery bootstrap json 学习中 第一次学PHP,正在研究中。自学进行时... ... 我的博客 https://enhweb.github.io/ 不错的皮肤:darkgreentrip,iMetro_HD
随笔 - 1079, 文章 - 1, 评论 - 75, 阅读 - 174万
  首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

WPF之单例模式

Posted on   WebEnh  阅读(56)  评论(0编辑  收藏  举报
 

问题

2019年10月9日星期三 上午2:46

1、为了实现单例模式,在App类中添加了如下代码,使用了信号量,但是为什么返回;isNew一直为true

public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            bool isNew=false;
            Mutex mutex = new Mutex(true, "MySingleInstance", out isNew);
            if(!isNew)
            {
                ActivateOtherWindow();
                Shutdown();
            }
            GC.KeepAlive(isNew);
        }

        private static void ActivateOtherWindow()
        {
            var other = Win32Api.FindWindow(null, "MainWindow");
            if (other != IntPtr.Zero)
            {
                Win32Api.SetForegroundWindow(other);
                if (Win32Api.IsIconic(other))
                    Win32Api.OpenIcon(other);
            }
        }
    }

全部回复 (2)

2019年10月9日星期三 上午6:35 ✅已答复 | 1 票

private Mutex mutex = null;

private void CheckSingleInstanceAndStartMainApp(string title)
        {
            bool isNew = false;
            if (null == mutex)
                mutex = new Mutex(true, "PowerPixel", out isNew);
            if (!isNew)
            {
                ActiveAndShowToFront(title);
                Environment.Exit(0);//强制退出,不会有弹框提示
            }
        }

        private void ActiveAndShowToFront(string titleName)
        {
            //s1:通过WAPi:FindWindow获取运行实例的句柄
            //或者事先保存实例,传递过来           
            IntPtr hwnd = Win32Api.FindWindow(null, titleName);

            if (hwnd != IntPtr.Zero)
            {
                Win32Api.SetForegroundWindow(hwnd);
                if (Win32Api.IsIconic(hwnd))
                    Win32Api.OpenIcon(hwnd);
            }
        }


2019年10月9日星期三 上午3:32

mutex不能被回收

 https://learn.microsoft.com/zh-cn/archive/msdn-technet-forums/bd78928c-890e-435d-acd6-6efc83590975
 

 

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2019-05-27 cshtml 中的 AppState = Context.Application 和 控制器中的 Application 也相等
点击右上角即可分享
微信分享提示

喜欢请打赏

扫描二维码打赏

了解更多