Skip to content

Commit

Permalink
move WindowListener's stop lock from dispose to stop method
Browse files Browse the repository at this point in the history
  • Loading branch information
Aytackydln committed Nov 4, 2024
1 parent 4b2fe8c commit 36bd86c
Showing 1 changed file with 19 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public sealed class WindowListener : IDisposable
private readonly object _disposeLock = new();

// using Automation as it is being disposed is BAD!
private bool _disposed;
private bool _stopped;

public WindowListener()
{
Expand All @@ -72,14 +72,18 @@ public void StartListening()

public void StopListening()
{
Automation.RemoveAutomationEventHandler(WindowPattern.WindowOpenedEvent, AutomationElement.RootElement, _automationEventHandler);
_stopped = true;
lock (_disposeLock)
{
Automation.RemoveAutomationEventHandler(WindowPattern.WindowOpenedEvent, AutomationElement.RootElement, _automationEventHandler);
}
}

private void WindowDetected(object? sender, AutomationEventArgs e)
{
lock (_disposeLock)
{
if (_disposed)
if (_stopped)
{
return;
}
Expand All @@ -97,15 +101,23 @@ private void WindowDetected(object? sender, AutomationEventArgs e)

var processId = process.Id;

if (_disposed)
if (_stopped)
{
return;
}

Automation.AddAutomationEventHandler(WindowPattern.WindowClosedEvent, element, TreeScope.Element, (_, _) =>
{
ProcessWindowsMap.Remove(name, new WindowProcess(windowHandle));
WindowDestroyed?.Invoke(this, new WindowEventArgs(name, processId, windowHandle, false));
lock (_disposeLock)
{
if (_stopped)
{
return;
}

ProcessWindowsMap.Remove(name, new WindowProcess(windowHandle));
WindowDestroyed?.Invoke(this, new WindowEventArgs(name, processId, windowHandle, false));
}
});

//To make sure window close event can be fired, we fire open event after subscribing to close event
Expand All @@ -121,11 +133,7 @@ private void WindowDetected(object? sender, AutomationEventArgs e)

public void Dispose()
{
_disposed = true;
lock (_disposeLock)
{
StopListening();
}
StopListening();
}

public sealed class WindowListenerReference : IDisposable
Expand All @@ -148,7 +156,6 @@ public WindowListenerReference()
}
}


public void Dispose()
{
lock(Instances)
Expand Down

0 comments on commit 36bd86c

Please sign in to comment.