/// <summary> /// Invoke handler method with associated dispatcher /// </summary> /// <param name="sender">Sender of event</param> /// <param name="args">Arguments</param> /// <remarks> /// Only invoke handlers method if. /// a) Subscriber is still alive (not claimed by GC) /// b) Subscriber thread is alive /// </remarks> public void Invoke(Dispatcher currentDispatcher, object sender, EventArgs args) { // Obtaining strong refereces object target = this.Target; Dispatcher dispatcher = this.Dispatcher; if (currentDispatcher.Equals(dispatcher)) { // Handlers is subscribed in current thread this.handlerInfo.Invoke(target, new object[] { sender, args }); } else if (dispatcher.Thread.GetApartmentState() == ApartmentState.STA) { // Handlers is subscribed in UI thread // Only handles for UI controls should be called in thread own thread // otherwise non-UI threads may be in lock wait state dispatcher.Invoke(new Action(() => this.handlerInfo.Invoke(target, new object[] { sender, args })), null); } else { // If thread is not marked with STA then its handlers can be called from other threads this.handlerInfo.Invoke(target, new object[] { sender, args }); } }