Search code examples
c#wpfui-automationmicrosoft-ui-automation

Subscribing to UI Automation event freezes application on window hang


I'm using AddPropertyChangedEventHandler to subscribe to a window event as per http://msdn.microsoft.com/en-us/library/ms752286(v=vs.110).aspx

However, if the target window hangs or freezes (unfortunately this can happen fairly regularly), my entire application hangs as well.

What is the best way to overcome this problem?

(C#, .NET 4.5, WPF)


Solution

  • See:

    Trying to install an event handler from an STA thread tends to deadlock as UIA tries to call back to the STA thread to notify it of the new event handler.

    According to that I believe you need to subscribe to the events on a different thread (i.e. not your UI thread)....it should be one that is initialized to use the COM MTA (multi-threaded apartment) threading model....rather that doing it on your UI's STA thread.

    Then just Invoke back to your UI thread, when you get the event on the background MTA thread (I would suggest using BeginInvoke rather than Invoke to call back to a delegate on your UI thread to avoid possible deadlocks).