我有一個內置于 Visual Studio 的 Windows 應用程式,該應用程式將部署到具有多個用戶的其他 PC 上,我想阻止我的應用程式多次運行,有沒有辦法以編程方式阻止它?或以其他方式?
uj5u.com熱心網友回復:
為此,您可以使用命名的互斥鎖。named(!) 互斥體是系統范圍的同步物件。我在我的專案中使用以下類(稍微簡化)。它在建構式中創建一個最初無主的互斥體,并在物件生命周期內將其存盤在成員欄位中。
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();
}
}
}
uj5u.com熱心網友回復:
您可以使用此代碼段來檢查實體是否正在運行,并可以提醒用戶另一個實體正在運行
static bool IsRunning()
{
return Process.GetProcesses().Count(p => p.ProcessName.Contains(Assembly.GetExecutingAssembly().FullName.Split(',')[0]) && !p.Modules[0].FileName.Contains("vshost")) > 1;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/366561.html
