如何限制应用多实例运行?需区分DeveloperBuild与ClientBuild版本
Solution for Per-Build Single Instance Enforcement
Got it, let's sort this out! The issue with your current code is that you're using a hardcoded, fixed mutex name ("MutexForMyApp") for both builds. That's why both DeveloperBuild and ClientBuild are hitting the same mutex—so they block each other even though they're different versions.
The fix is simple: tie the mutex name to your assembly's actual name, which differs between your two builds (DeveloperBuild vs ClientBuild). Here's how to adjust your code:
Step-by-Step Adjustment
- Dynamically get the assembly name: Use the entry assembly's name to create a unique mutex per build.
- Update the mutex name: Replace the hardcoded string with one that includes the assembly name.
- Properly release the mutex: Add cleanup logic to release the mutex when the app exits, which is good practice.
Modified Code
private Mutex _mutex; protected override void OnStartup(StartupEventArgs e) { // Get the entry assembly name (will be "DeveloperBuild" or "ClientBuild") string assemblyName = System.Reflection.Assembly.GetEntryAssembly()?.GetName().Name ?? "DefaultAppName"; // Create a mutex name unique to the build version string mutexUniqueName = $"MutexForMyApp_{assemblyName}"; bool createdNew; _mutex = new Mutex(true, mutexUniqueName, out createdNew); if (!createdNew) { MessageBox.Show($"A instance of {assemblyName} is already running!", assemblyName, MessageBoxButton.OK, MessageBoxImage.Exclamation); Application.Current.Shutdown(); return; } base.OnStartup(e); var bootstrapper = new Bootstrapper(); bootstrapper.Run(); } protected override void OnExit(ExitEventArgs e) { _mutex?.ReleaseMutex(); _mutex?.Dispose(); base.OnExit(e); }
How This Works
- The
assemblyNamevariable grabs the actual name of your build's assembly, so each version gets its own distinct mutex name (e.g.,"MutexForMyApp_DeveloperBuild"and"MutexForMyApp_ClientBuild"). - Now, when you launch DeveloperBuild, it checks its own mutex—if it's already running, it blocks. Same for ClientBuild. But since their mutexes are different, you can run one instance of each at the same time, exactly as you need.
- The
OnExitmethod ensures we clean up the mutex properly when the app closes, avoiding leftover mutex handles.
Notes
- The null coalescing (
?? "DefaultAppName") is a safety net in caseGetEntryAssembly()returns null (rare, but possible in some edge cases). - Make sure your two builds actually have different assembly names configured in your project settings—you mentioned they do, so this should align perfectly.
内容的提问来源于stack exchange,提问作者DotNetSpartan
相关产品推荐
相关产品推荐

