Skip to content

Commit

Permalink
Fix to have only one PI instance at any point in time (#2951)
Browse files Browse the repository at this point in the history
* redirect to the elevated instance if present

* add stopevent

* PR feedback
  • Loading branch information
zadesai authored May 17, 2024
1 parent 5e500fb commit 2b55fc4
Showing 1 changed file with 41 additions and 6 deletions.
47 changes: 41 additions & 6 deletions tools/PI/DevHome.PI/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,18 @@ public static void Main(string[] args)
.ReadFrom.Configuration(configuration)
.CreateLogger();

var stopEvent = new EventWaitHandle(false, EventResetMode.ManualReset, $"DevHomePI-{Environment.ProcessId}");
ThreadPool.QueueUserWorkItem((o) =>
{
var waitResult = stopEvent.WaitOne();

_app?.UIDispatcher?.TryEnqueue(() =>
{
var primaryWindow = Application.Current.GetService<PrimaryWindow>();
primaryWindow.Close();
});
});

try
{
XamlCheckProcessRequirements();
Expand All @@ -67,6 +79,9 @@ public static void Main(string[] args)
OnActivated(null, AppInstance.GetCurrent().GetActivatedEventArgs());
});
}

stopEvent.Close();
stopEvent.Dispose();
}
catch (Exception ex)
{
Expand All @@ -80,25 +95,45 @@ public static void Main(string[] args)

private static async Task<bool> DecideRedirection()
{
AppInstance instance;
var activatedEventArgs = AppInstance.GetCurrent().GetActivatedEventArgs();
if (RuntimeHelper.IsCurrentProcessRunningAsAdmin())
var isElevatedInstancePresent = false;
var isUnElevatedInstancePresent = false;
var instanceList = AppInstance.GetInstances();
foreach (var appInstance in instanceList)
{
if (appInstance.Key.Equals(MainInstanceKey, StringComparison.OrdinalIgnoreCase))
{
isUnElevatedInstancePresent = true;
}
else if (appInstance.Key.Equals(ElevatedInstanceKey, StringComparison.OrdinalIgnoreCase))
{
isElevatedInstancePresent = true;
}
}

AppInstance instance;
if (isElevatedInstancePresent)
{
// Redirect to the elevated instance if present.
instance = AppInstance.FindOrRegisterForKey(ElevatedInstanceKey);
}
else if (RuntimeHelper.IsCurrentProcessRunningAsAdmin())
{
// Wait for unelevated instance to exit
var isUnElevatedInstancePresent = false;
do
while (isUnElevatedInstancePresent)
{
isUnElevatedInstancePresent = false;
var instanceList = AppInstance.GetInstances();
instanceList = AppInstance.GetInstances();
foreach (var appInstance in instanceList)
{
if (appInstance.Key.Equals(MainInstanceKey, StringComparison.OrdinalIgnoreCase))
{
isUnElevatedInstancePresent = true;
var stopAppInstance = new EventWaitHandle(false, EventResetMode.ManualReset, $"DevHomePI-{appInstance.ProcessId}");
stopAppInstance.Set();
}
}
}
while (isUnElevatedInstancePresent);

// Register the elevated instance key
instance = AppInstance.FindOrRegisterForKey(ElevatedInstanceKey);
Expand Down

0 comments on commit 2b55fc4

Please sign in to comment.