首页 新闻 会员 周边 捐助

Mutex在创建以后必须使用ReleaseMutex()释放一次吗

0
[已解决问题] 解决于 2023-02-23 16:13
static void Main()
        {
            bool createdNew;                                    
            Mutex mutex = new Mutex(false, "Single", out createdNew);
        
            if (!createdNew)                                      
            {
                Process currentProcess = Process.GetCurrentProcess();
                foreach (Process process in Process.GetProcessesByName(currentProcess.ProcessName))
                {
                    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;
            }
            else
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new MainFrame());
                //mutex.ReleaseMutex();       //释放Mutex一次
            }
        }

我这样写,在关闭窗体的时候释放那里会报错:

PixelKiwi的主页 PixelKiwi | 菜鸟二级 | 园豆:262
提问于:2023-02-23 15:10
< >
分享
最佳答案
0

mutex.ReleaseMutex() 需要对应 mutex.WaitOne(),没有 WaitOne 直接 ReleaseMutex 就会报错

Object synchronization method was called from an unsynchronized block of code
奖励园豆:5
dudu | 高人七级 |园豆:30939 | 2023-02-23 15:34

哦哦哦,我在创建之后加上了,就不报错了。那么写对呗

PixelKiwi | 园豆:262 (菜鸟二级) | 2023-02-23 15:58

@BoiledYakult: 参考园子里的博文:C# 针对特定的条件进行锁操作,不用lock,而是mutex

dudu | 园豆:30939 (高人七级) | 2023-02-23 16:00

@dudu: 好

PixelKiwi | 园豆:262 (菜鸟二级) | 2023-02-23 16:13
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册