ViewModel and property updates on background thread

ViewModel and property updates on background thread

Old forum URL:

Turntwo posted on Friday, June 01, 2012

I'm working in a MVVM project using ViewModelBase.  Working quite well for the most part, but I ran into an issue and I'm not sure if there is a workaround or I'm just trying to do something I shouldn't do. 

I have a Model object, and based on some stuff happening on a background thread (input from a WCF service message), I want to update a property of the Model.  The property update works fine (using LoadProperty), but if I call OnPropertyChanged from the background thread, the ViewModel blows up in SetProperties (can't access the Model because it is owned by the UI thread).  I would like the property to be updated in the UI when it is changed, but appears this can't be done in the background? 

I tried forcing SetProperties to run using the Dispatcher.Invoke, but then I received a similar error on CanCreateObject.  

Does anyone have a way to notify of the property change from the background thread (I don't really want to include any Dispatch logic in my Business classes, for obvious reasons).  

RockfordLhotka replied on Monday, June 04, 2012

Like much of .NET, CSLA isn't threadsafe. You should never update property values on an object using a background thread.

Or if you must do that, you must first ensure that the object is not bound to any UI elements, or any other objects that might be bound to a UI or be in use by other threads.

In other words, an object graph can only be used by one thread at a time, and data binding also binds the object graph to the UI thread. (this last part is because none of the .NET UI technologies are threadsafe either, and they all only work when carefully following threading rules).

What I do in these cases, is run the worker code on the background thread, and then marshal the result to the UI thread, and then update the property of the business object.

CSLA elements like the data portal, Csla.Threading.BackgroundWorker, the new async/await features in version 4.5, the viewmodelbase class, and others all try to automatically do this marshalling for you.

For example, if you encapsulate your WCF service call in a business object and use the data portal in local mode, you can allow the data portal to help you with the marshalling process, so by the time the data portal call returns with the business object containing the information, it will already be on the UI thread and therefore safe to use.

Copyright (c) Marimer LLC