My WPF program loads data from multiple CSV files into a Line Chart (each file into its own LineSeries). This takes some time (rendering the GUI unusable) so I wanted to do this operation in a seperate thread and display a loading message (The BusyIndicator from the Extended WPF Toolkit).
Unfortunately when I try to create a LineSeries in the BackgroundWorker, I get an exception: “The calling thread must be STA, because many UI components require this.” I’m trying to copy the GUI’s chart, populate the copy, then it to the GUI’s chart upon completion. So this shouldn’t be trying to access a control from a different thread.
/// <summary>
/// Loads data from the collections into the chart
/// </summary>
private void populateChart()
{
// Begin working: Pass chart and data to the worker (wrapped in a class)
this.chartWorker.RunWorkerAsync(new ChartWorkerArgs()
{
chart = chart,
data = model.getAllCollections()
});
}
/// <summary>
/// Populates a provided Chart with provided data.
/// </summary>
private void chartWorker_DoWork(object sender, DoWorkEventArgs e)
{
// ...
// Iterate through each one
foreach (XYCollection collection in data)
{
// Create a new LineSeries and configure it
LineSeries ls = new LineSeries(); // <-----------ERROR
ls.ItemsSource = collection;
ls.IndependentValueBinding = new Binding("X");
ls.DependentValueBinding = new Binding("Y");
ls.Title = collection.Name;
chart.Series.Add(ls);
}
// Send the pouplated chart back
e.Result = chart;
}
/// <summary>
/// After chart has been populated (or cancelled), update chart.
/// </summary>
private void chartWorker_RunWorkerCompleted(
object sender, RunWorkerCompletedEventArgs e)
{
// ...
// Set the GUI's chart as the newly populated chart
this.chart = (Chart)e.Result;
// ...
}
From what I’ve read elsewhere, its not possible to make a BackgroundWorker STA, so is there some other way I can load the chart with data without hanging the GUI?
Thanks
You could use a plain Thread. Then you have the control (ownership) to make it STA.
The Bgw adds just a few handy features to interact with the GUI, nothing you can’t write yourself in a few lines of code. You’re not even using the UpdateProgress.