SOLVED: "The calling thread cannot access this object because a different thread owns it"

8. July 2010

When writing a WPF application using MVVM I  came across this exception when throwing events up to the UI. The problem was that the source events were being thrown from a SmartCard API on a separate thread and I needed to bubble an event up to the UI to update an ObservableCollection in the ViewModel of the current Window.

The problem was I need to cast the DataContext to the correct ViewModel and in order to do that I needed to be on the UI thread. To solve the problem you need to use the Dispatcher but in a very specific way in order to do the cast. Below is the code example I used:

// Need to use the dispatcher with the new SmartCard assemblies to check if needed
// There is a warehouse selection dropdown on the left menu.  This Init() causes it to hook up to 
// the SessionSecurity.UserAuthenticationChanged event to populate that dropdown.
if (!leftMenu.Dispatcher.CheckAccess()) { // Use BeginInvoke with this delegate to pass method as parameter
// without declaring a custom delegate.
Dispatcher.BeginInvoke(new Action(() => { ((LeftMenuControlViewModel)leftMenu.DataContext).EvaluateUserState(); }), System.Windows.Threading.DispatcherPriority.Normal); } else { ((LeftMenuControlViewModel)leftMenu.DataContext).EvaluateUserState(); }

.Net Framework 4.0, C# ,