日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

如何阻止给 一个程序 开启多个实例 ?

發(fā)布時間:2023/12/4 编程问答 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 如何阻止给 一个程序 开启多个实例 ? 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

咨詢區(qū)

  • C. Dragon 76

在 .NET 中是否有比較好的方法可以阻止一個 application 被同時開啟了多個實例?如果沒有好的辦法,那么只能退其次,給每個 application 配一些操作規(guī)范。

回答區(qū)

  • ImJustPondering

我總結(jié)有兩種解法。

  • 使用 Meutx。

  • [STAThread] static?void?Main()? {using(Mutex?mutex?=?new?Mutex(false,?"Global\\"?+?appGuid)){if(!mutex.WaitOne(0,?false)){MessageBox.Show("Instance?already?running");return;}Application.Run(new?Form1());} }private?static?string?appGuid?=?"c0a76b5a-12ab-45c5-b9d9-d693faa6e7b9";

    關(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)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。