Monday, March 26, 2012

Nasty Exceptions with Threaded MVVM Application

Consider to work with the private variable of a property versus the public property itself if you are implementing INotifyPropertyChanged. More specifically, if you have your OnPropertyChanged event in the Set block of your property as this makes a call to the Main Thread of your application to update the view (which you probably already knew).

Here is an example…

This property calls the OnPropertyChanged event every time the property is set.

        Private _salesOrderItemView As DataView = Nothing

        Public Property SalesOrderItemView As DataView

            Get

                Return _salesOrderItemView

            End Get

            Set(ByVal value As DataView)

                _salesOrderItemView = value

                OnPropertyChanged("SalesOrderItemView")

            End Set

        End Property

                                                         

And if you populate the property

SalesOrderItemView = dsTemp.Tables(0).DefaultView



Then add a column

SalesOrderItemView.Table.Columns.Add("NewColumn")



And do a For Each loop

For Each row As DataRow In SalesOrderItemView.Table.Rows

       ‘’Do something

Next



If it is quick enough, you will get a nasty exception.

Why? I am not really sure, but I think it has to do with adding a row and be in the iteration of the For Each loop. It seems to me that if you are adding the row, which will call the OnPropertyChanged event and update the view in the main thread, it will continue to execute the background thread. If it is fast enough to get into the For Each loop while the view is being updated, it will take away the object reference to the view.

Though, if I put a couple of lines of code between the adding a column statement and the For Each loop, the view will have enough time to get updated and no exception will be thrown.

Commenting out the OnPropertyChanged event will also avoid an exception being thrown.
Any comments on this?

No comments:

Post a Comment