我需要禁止从同一文件夹启动的应用程序,但如果同一应用程序从其他文件夹运行则允许它。
问题是当应用程序关闭时,它变得不可见但仍然在内存中,因为它终止了一些内部作业。
当旧实例仍在内存中终止时,用户很可能会从同一文件夹快速再次启动此应用程序。
但从另一方面来看,如果此应用程序从其他文件夹运行,应该是可能的。
有什么线索可以用 C# 实现吗?
更新:
1
事实上,应用程序将一些日志写入子目录中的本地文件以及本地数据库文件中。所以这很可能是两个实例之间的一些冲突。
2
Guid appGuid = Guid.Parse("305BACEA-4074-11E1-85E1-066E4854019B");
public MainWindow()
{
InitializeComponent();
using (Mutex mutex = new Mutex(false, @"Global\" + appGuid) )
{
if (!mutex.WaitOne(0, false))
{
// MessageBox.Show("Instance already running");
// Somehow here I have to get the path of the running instance.
// If the path the same as the current instance has I have do ban starting instance.
return;
}
GC.Collect();
}
最佳答案
谢谢大家!
最后基于这个post我找到了解决方案:
public partial class App : Application
{
private Mutex _instanceMutex = null;
protected override void OnStartup(StartupEventArgs e)
{
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location).Replace("\\", ".");
// check that there is only one instance of the control panel running...
bool createdNew;
_instanceMutex = new Mutex(true, path, out createdNew);
if (!createdNew)
{
_instanceMutex = null;
MessageBox.Show("Instance already running");
Application.Current.Shutdown();
return;
}
base.OnStartup(e);
}
protected override void OnExit(ExitEventArgs e)
{
if (_instanceMutex != null)
_instanceMutex.ReleaseMutex();
base.OnExit(e);
}
}
关于c# - 如何确定某个位置的 .NET 应用程序实例是否正在运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8884499/