1

Sometimes when I call RaiseEvent CanExecuteChanged(sender, EventArgs.Empty) from a back ground thread it give me an exception stating "The calling thread cannot access this object because a different thread owns it."

However, if I call System.Windows.Threading.Dispatcher.CurrentDispatcher.CheckAccess is returns True.

What am I doing wrong?

Private Sub m_Parent_PropertyChanged(ByVal sender As Object, ByVal e As PropertyChangedEventArgs) Handles m_Parent.PropertyChanged
    If System.Windows.Threading.Dispatcher.CurrentDispatcher.CheckAccess Then
        RaiseEvent CanExecuteChanged(sender, EventArgs.Empty)
    Else

    End If
End Sub
Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
Jonathan Allen
  • 68,373
  • 70
  • 259
  • 447
  • Could you please provide information on where the exception is being thrown from? You are implying that the call to RaiseEvent is throwing the exception, but in fact, it'll be something that has handled your CanExecuteChanged event. A stack trace would be useful. If it looks like it really is coming from RaiseEvent, what that probably means is that the exception is coming from inside a .NET Framework class. In which case, right-click on the stack trace, and enable the option to show 'external code' to see where it's really coming from. – Ian Griffiths Nov 04 '10 at 23:22
  • The problem is that `CurrentDispatcher.CheckAccess` is not a valid design pattern. You need to check the dispatcher associated with the objects receiving the events. – Jonathan Allen Nov 07 '10 at 10:02
  • Hi, I have exactly the same problem, can you please explain to reference the main thread's dispatcher in detail? Thanks alot. –  Mar 08 '11 at 07:24
  • It is ugly. Really ugly. I cannot get into it now, but if you send me a reminder this weekend I'll look up the code for you. grauenwolf@gmail.com. – Jonathan Allen Mar 09 '11 at 23:23

2 Answers2

2
Application.Current.Dispatcher.CheckAccess()

see also : Ensuring that things run on the UI thread in WPF

Community
  • 1
  • 1
Simon_Weaver
  • 140,023
  • 84
  • 646
  • 689
2

System.Windows.Threading.Dispatcher.CurrentDispatcher.CheckAccess will always return true as thread always has an access to the Dispatcher associated with it. The problem is that you are using dispatcher of a background thread and not of main thread where UI is running.

If you need to raise CanExecuteChanged you can save a reference to the main thread's dispatcher and use its Invoke method.

StanislawSwierc
  • 2,571
  • 17
  • 23