如何阻止给 一个程序 开启多个实例 ?
生活随笔
收集整理的這篇文章主要介紹了
如何阻止给 一个程序 开启多个实例 ?
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
咨詢區(qū)
C. Dragon 76:
在 .NET 中是否有比較好的方法可以阻止一個 application 被同時開啟了多個實例?如果沒有好的辦法,那么只能退其次,給每個 application 配一些操作規(guī)范。
回答區(qū)
ImJustPondering:
我總結(jié)有兩種解法。
使用 Meutx。
關(guān)于 Mutex 更多資料,可參考:http://odetocode.com/Blogs/scott/archive/2004/08/20/401.aspx
使用 Process
可以迭代進程列表,判斷是否已經(jīng)存在該進程名即可,參考如下代碼:
using?System.Diagnostics; .... [STAThread] static?void?Main() { ...int?procCount?=?0;foreach?(Process?pp?in?Process.GetProcesses()){try{if?(String.Compare(pp.MainModule.FileName,?Application.ExecutablePath,?true)?==?0){procCount++;????????????????????????if(procCount?>?1)?{Application.Exit();return;}}}catch?{?}}Application.Run(new?Form1()); }Tono Nam:
其實可以仿 linux 上生成進程文件的方式,所以要做的就是在程序啟動后,在某一個文件中寫入一個默認的 uniqueid 值,參考如下代碼:
public?static?void?PreventMultipleInstance(string?applicationId){//?Under?Windows?this?is://??????C:\Users\SomeUser\AppData\Local\Temp\?//?Linux?this?is://??????/tmp/var?temporaryDirectory?=?Path.GetTempPath();//?Application?ID?(Make?sure?this?guid?is?different?accross?your?different?applications!var?applicationGuid?=?applicationId?+?".process-lock";//?file?that?will?serve?as?our?lockvar?fileFulePath?=?Path.Combine(temporaryDirectory,?applicationGuid);try{//?Prevents?other?processes?from?reading?from?or?writing?to?this?filevar?_InstanceLock?=?new?FileStream(fileFulePath,?FileMode.OpenOrCreate,?FileAccess.ReadWrite,?FileShare.None);_InstanceLock.Lock(0,?0);MonoApp.Logger.LogToDisk(LogType.Notification,?"04ZH-EQP0",?"Aquired?Lock",?fileFulePath);//?todo?investigate?why?we?need?a?reference?to?file?stream.?Without?this?GC?releases?the?lock!System.Timers.Timer?t?=?new?System.Timers.Timer(){Interval?=?500000,Enabled?=?true,};t.Elapsed?+=?(a,?b)?=>{try{_InstanceLock.Lock(0,?0);}catch{MonoApp.Logger.Log(LogType.Error,?"AOI7-QMCT",?"Unable?to?lock?file");}};t.Start();}catch{//?Terminate?application?because?another?instance?with?this?ID?is?runningEnvironment.Exit(102534);?}}點評區(qū)
這個需求本質(zhì)上和防重復登錄時一樣的,大概三種吧:
機器內(nèi)作用域:
Metux,Process 是一個好辦法。
跨機器或局域網(wǎng)作用域:
生成 PID 文件是一個好辦法。
局域網(wǎng),廣域網(wǎng):
可用 redis,zookeeper 之類的全局鎖機制。
總結(jié)
以上是生活随笔為你收集整理的如何阻止给 一个程序 开启多个实例 ?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 值得永久收藏的 C# 设计模式套路(一)
- 下一篇: 手把手教你学Dapr - 5. 状态管理