In my ViewModel I have a ObservableCollection of type Point which is bound to one of the chart's series within the View. When the user clicks a button the an asynchronous call is made to a method which executes a computationally intensive calculation and updates the ObservableCollection throughout the process.
When it gets to the line that updates an element within the ObservableCollection an
InvalidOperationException
is thrown with the explanation that "The calling thread cannot access this object because a different thread owns it." I understand that this is occurring because I am trying to change an object which is bound to a control on the UI thread.
How do people typically deal with this problem? I'm hoping there is a very clean and straightforward way? Or do I have to make a call using a delegate to invoke on the ObservableCollection?
Update with more information:
I didn't use the
.ConfigureAwait
when launching the asynchronous method. Simply:
<br />
await Task.Factory.StartNew(() => methodName(parameter1));
A little more information I gathered while trying to get this to work. Initially I had an
ObservableCollection
of type
System.Windows.Point
which has an
X
and a
Y
property which is being used in the chart. Because the
X
and
Y
do not have a
Set
attribute I had to create a new
Point
element looking something like
<br />
observableCollection1[0] = new System.Windows.Point(newPointX, newPointY);<br />
It is at that line where the
InvalidOperationException
is thrown.
I tried it another way of creating a
List
of type
Point
and added each new newXPoint and newYPoint value to the list and then outside the loop created a new
ObservableCollection
object initialized with the
List
elements like so:
<br />
observableCollection1 = new ObservableCollection<system.windows.point>(tempList);</system.windows.point>
This does not throw the
InvalidOperationException
and seems to work fine. I imagine this is probably the better way to do it as well since the NotifyPropertyChanged event will only fire once instead of every time that an element set to a new instance of a
Point
object. Is that correct??
Regardless of which method is better I am still very confused why I am getting the InvalidOperationException. Any thoughts?