I am having this error again: The calling thread cannot access this object because a different thread owns it.
Here is my code:
public void InitiateSignalAnalysisPlot()
{
if (_nActiveChannel > 0) // timeDomainPlotter init
{
_dataX = new List<double[]>();
_dataY = new List<double[]>();
_dataX3 = new List<List<double[]>>();
_dataY3 = new List<List<double[]>>();
double[] dataXOneCh = new double[1];
double[] dataYOneCh = new double[1];
dataXOneCh[0] = 0;
dataYOneCh[0] = 0;
CirclePointMarker pm = new CirclePointMarker { Size = 5, Fill = Brushes.Transparent };
for (int i = 0; i < _nActiveChannel; i++)
{
if (_nActiveStatsOneChannel > 0)
{
for (int j = 0; j < _nActiveStatsOneChannel; j++)
{
_dataX.Add(dataXOneCh); // data x-y mapping init
_dataY.Add(dataYOneCh);
EnumerableDataSource<double> xOneCh = new EnumerableDataSource<double>(dataXOneCh);
EnumerableDataSource<double> yOneCh = new EnumerableDataSource<double>(dataYOneCh);
xOneCh.SetXMapping(xVal => xVal);
yOneCh.SetXMapping(yVal => yVal);
CompositeDataSource dsOneCh = new CompositeDataSource(xOneCh, yOneCh);
Action InitiatePlotter = delegate()
{
LineAndMarker<MarkerPointsGraph> lam = timeDomainPlotter.AddLineGraph(dsOneCh,
new Pen(pm.Fill, 2),
pm,
new PenDescription("C" + Convert.ToString(i) + "S" + Convert.ToString(j)));
};
this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, InitiatePlotter);
}
_dataX3.Add(_dataX);
_dataY3.Add(_dataY);
}
}
timeDomainPlotter.FitToView();
}
else
{
return;
}
}
The error occurs at "this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, InitiatePlotter);"
This is a piece of code behind a WPF window called by the main window thread. I am confused that I have used dispatcher.invoke() to void this multithread conflicting, why I am still getting this error? If I put this piece of code int he constructor of the window being called, it works, but I just don't want to do that way. What change can I make to I avoid this error? Thanks.
More information that might help : The timeDomainPlotter is in wpf window B, which is initiated (WindowB _windowB = new WindowB(); ) in window A; The code above, InitiateSignalAnalysisPlot(), is also in window B, but InitiateSignalAnalysisPlot() gets called in window A, something like _windowB,InitiateSignalAnalysisPlot();
If I don't Dispatcher.Invoke() it, there will also be an exception, which is The calling thread must be STA, because many UI components require this.
, happening at
LineAndMarker<MarkerPointsGraph> lam = timeDomainPlotter.AddLineGraph(dsOneCh,
new Pen(pm.Fill, 2),
pm,
new PenDescription("C" + Convert.ToString(i) + "S" + Convert.ToString(j)));