[英]Prevent my windows application to run multiple times
我在 Visual Studio 中構建了一個 windows 應用程序,該應用程序將部署到具有多個用戶的其他 PC 上,我想阻止我的應用程序多次運行有什么方法可以以編程方式阻止它? 或以其他方式?
您可以為此目的使用命名互斥鎖。 named(.) 互斥鎖是系統范圍的同步 object。 我在我的項目中使用以下 class (略微簡化)。 它在構造函數中創建一個最初無主的互斥體,並在 object 生命周期內將其存儲在成員字段中。
public class SingleInstance : IDisposable
{
private System.Threading.Mutex _mutex;
// Private default constructor to suppress uncontrolled instantiation.
private SingleInstance(){}
public SingleInstance(string mutexName)
{
if(string.IsNullOrWhiteSpace(mutexName))
throw new ArgumentNullException("mutexName");
_mutex = new Mutex(false, mutexName);
}
~SingleInstance()
{
Dispose(false);
}
public bool IsRunning
{
get
{
// requests ownership of the mutex and returns true if succeeded
return !_mutex.WaitOne(1, true);
}
}
public void Dispose()
{
GC.SuppressFinalize(this);
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
try
{
if(_mutex != null)
_mutex.Close();
}
catch(Exception ex)
{
Debug.WriteLine(ex);
}
finally
{
_mutex = null;
}
}
}
這個例子展示了如何在程序中使用它。
static class Program
{
static SingleInstance _myInstance = null;
[STAThread]
static void Main()
{
// ...
try
{
// Create and keep instance reference until program exit
_myInstance = new SingleInstance("MyUniqueProgramName");
// By calling this property, this program instance requests ownership
// of the wrapped named mutex. The first program instance gets and keeps it
// until program exit. All other program instances cannot take mutex
// ownership and exit here.
if(_myInstance.IsRunning)
{
// You can show a message box, switch to the other program instance etc. here
// Exit the program, another program instance is already running
return;
}
// Run your app
}
finally
{
// Dispose the wrapper object and release mutex ownership, if owned
_myInstance.Dispose();
}
}
}
您可以使用此代碼段檢查實例是否正在運行,並可以提醒用戶另一個實例正在運行
static bool IsRunning()
{
return Process.GetProcesses().Count(p => p.ProcessName.Contains(Assembly.GetExecutingAssembly().FullName.Split(',')[0]) && !p.Modules[0].FileName.Contains("vshost")) > 1;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.